context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Collections.Specialized;
#if !(NET_1_1)
using System.Collections.Generic;
using FluorineFx.Collections.Generic;
#endif
using FluorineFx.Util;
using FluorineFx.Collections;
using FluorineFx.Messaging.Api;
namespace FluorineFx.Messaging
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
[CLSCompliant(false)]
public class AttributeStore : DisposableBase, IAttributeStore
{
/// <summary>
/// Attribute dictionary.
/// </summary>
#if !(NET_1_1)
protected CopyOnWriteDictionary<string, object> _attributes;
#else
protected CopyOnWriteDictionary _attributes;
#endif
/// <summary>
/// Initializes a new instance of the AttributeStore class.
/// </summary>
public AttributeStore()
{
#if !(NET_1_1)
_attributes = new CopyOnWriteDictionary<string,object>();
#else
_attributes = new CopyOnWriteDictionary();
#endif
}
#region IAttributeStore Members
/// <summary>
/// Returns the attribute names.
/// </summary>
/// <returns>Collection of attribute names.</returns>
#if !(NET_1_1)
public virtual ICollection<string> GetAttributeNames()
#else
public virtual ICollection GetAttributeNames()
#endif
{
return _attributes.Keys;
}
/// <summary>
/// Sets an attribute on this object.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <param name="value">The attribute value.</param>
/// <returns>true if the attribute value changed otherwise false.</returns>
public virtual bool SetAttribute(string name, object value)
{
if (name == null)
return false;
// Update with new value
object previous = null;
_attributes.TryGetValue(name, out previous);
if( previous == null || !value.Equals(previous) )
_attributes[name] = value;
return (previous == null || !value.Equals(previous));
}
#if !(NET_1_1)
/// <summary>
/// Sets multiple attributes on this object.
/// </summary>
/// <param name="values">Dictionary of attributes.</param>
public virtual void SetAttributes(IDictionary<string, object> values)
{
foreach (KeyValuePair<string, object> entry in values)
{
SetAttribute(entry.Key, entry.Value);
}
}
#endif
/// <summary>
/// Sets multiple attributes on this object.
/// </summary>
/// <param name="values">Dictionary of attributes.</param>
public virtual void SetAttributes(IDictionary values)
{
foreach (DictionaryEntry entry in values)
{
SetAttribute(entry.Key as string, entry.Value);
}
}
/// <summary>
/// Sets multiple attributes on this object.
/// </summary>
/// <param name="values">Attribute store.</param>
public virtual void SetAttributes(IAttributeStore values)
{
foreach (string name in values.GetAttributeNames())
{
object value = values.GetAttribute(name);
SetAttribute(name, value);
}
}
/// <summary>
/// Returns the value for a given attribute.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <returns>The attribute value.</returns>
public virtual object GetAttribute(string name)
{
if (name == null)
return null;
if (_attributes.ContainsKey(name))
return _attributes[name];
return null;
}
/// <summary>
/// Returns the value for a given attribute and sets it if it doesn't exist.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <param name="defaultValue">Attribute's default value.</param>
/// <returns>The attribute value.</returns>
public virtual object GetAttribute(string name, object defaultValue)
{
if (name == null)
return null;
if (defaultValue == null)
throw new NullReferenceException("The default value may not be null.");
if (_attributes.ContainsKey(name))
return _attributes[name];
else
{
_attributes[name] = defaultValue;
return null;
}
}
/// <summary>
/// Checks whetner the object has an attribute.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <returns>true if a child scope exists, otherwise false.</returns>
public virtual bool HasAttribute(string name)
{
if (name == null)
return false;
return _attributes.ContainsKey(name);
}
/// <summary>
/// Removes an attribute.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <returns>true if the attribute was found and removed otherwise false.</returns>
public virtual bool RemoveAttribute(string name)
{
if (HasAttribute(name))
{
_attributes.Remove(name);
return true;
}
return false;
}
/// <summary>
/// Removes all attributes.
/// </summary>
public virtual void RemoveAttributes()
{
_attributes.Clear();
}
/// <summary>
/// Gets whether the attribute store is empty;
/// </summary>
public bool IsEmpty
{
get
{
return _attributes.Count == 0;
}
}
/// <summary>
/// Gets or sets a value by name.
/// </summary>
/// <param name="name">The key name of the value.</param>
/// <returns>The value with the specified name.</returns>
public Object this[string name]
{
get
{
return GetAttribute(name);
}
set
{
SetAttribute(name, value);
}
}
/// <summary>
/// Gets the number of attributes in the collection.
/// </summary>
public int AttributesCount
{
get
{
return _attributes.Count;
}
}
#if !(NET_1_1)
/// <summary>
/// Copies the collection of attribute values to a one-dimensional array, starting at the specified index in the array.
/// </summary>
/// <param name="array">The Array that receives the values.</param>
/// <param name="index">The zero-based index in array from which copying starts.</param>
public void CopyTo(object[] array, int index)
{
_attributes.Values.CopyTo(array, index);
}
#else
/// <summary>
/// Copies the collection of attribute values to a one-dimensional array, starting at the specified index in the array.
/// </summary>
/// <param name="array">The Array that receives the values.</param>
/// <param name="index">The zero-based index in array from which copying starts.</param>
public void CopyTo(Array array, int index)
{
_attributes.Values.CopyTo(array, index);
}
#endif
/// <summary>
/// Returns an enumerator that iterates through an AttributeStore.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator GetEnumerator()
{
return _attributes.GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Contents;
using OrchardCore.FileStorage;
using OrchardCore.Lists.Indexes;
using OrchardCore.Lists.Models;
using OrchardCore.Media;
using OrchardCore.MetaWeblog;
using OrchardCore.Modules;
using OrchardCore.Security.Permissions;
using OrchardCore.Users.Services;
using OrchardCore.XmlRpc;
using OrchardCore.XmlRpc.Models;
using YesSql;
namespace OrchardCore.Lists.RemotePublishing
{
[RequireFeatures("OrchardCore.RemotePublishing")]
public class MetaWeblogHandler : IXmlRpcHandler
{
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IAuthorizationService _authorizationService;
private readonly IMediaFileStore _mediaFileStore;
private readonly IMembershipService _membershipService;
private readonly IEnumerable<IMetaWeblogDriver> _metaWeblogDrivers;
private readonly ISession _session;
private readonly IStringLocalizer S;
public MetaWeblogHandler(
IContentManager contentManager,
IAuthorizationService authorizationService,
IMembershipService membershipService,
ISession session,
IContentDefinitionManager contentDefinitionManager,
IMediaFileStore mediaFileStore,
IEnumerable<IMetaWeblogDriver> metaWeblogDrivers,
IStringLocalizer<MetaWeblogHandler> localizer)
{
_contentManager = contentManager;
_contentDefinitionManager = contentDefinitionManager;
_authorizationService = authorizationService;
_metaWeblogDrivers = metaWeblogDrivers;
_session = session;
_mediaFileStore = mediaFileStore;
_membershipService = membershipService;
S = localizer;
}
public void SetCapabilities(XElement options)
{
const string manifestUri = "http://schemas.microsoft.com/wlw/manifest/weblog";
foreach (var driver in _metaWeblogDrivers)
{
driver.SetCapabilities((name, value) => { options.SetElementValue(XName.Get(name, manifestUri), value); });
}
}
public async Task ProcessAsync(XmlRpcContext context)
{
if (context.RpcMethodCall.MethodName == "blogger.getUsersBlogs")
{
var result = await MetaWeblogGetUserBlogsAsync(context,
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value));
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.getRecentPosts")
{
var result = await MetaWeblogGetRecentPosts(
context,
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
Convert.ToInt32(context.RpcMethodCall.Params[3].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.newPost")
{
var result = await MetaWeblogNewPostAsync(
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
(XRpcStruct)context.RpcMethodCall.Params[3].Value,
Convert.ToBoolean(context.RpcMethodCall.Params[4].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.getPost")
{
var result = await MetaWeblogGetPostAsync(
context,
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.editPost")
{
var result = await MetaWeblogEditPostAsync(
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
(XRpcStruct)context.RpcMethodCall.Params[3].Value,
Convert.ToBoolean(context.RpcMethodCall.Params[4].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "blogger.deletePost")
{
var result = await MetaWeblogDeletePostAsync(
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
Convert.ToString(context.RpcMethodCall.Params[3].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.newMediaObject")
{
var result = await MetaWeblogNewMediaObjectAsync(
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
(XRpcStruct)context.RpcMethodCall.Params[3].Value);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
}
private async Task<XRpcStruct> MetaWeblogNewMediaObjectAsync(string userName, string password, XRpcStruct file)
{
var user = await ValidateUserAsync(userName, password);
var name = file.Optional<string>("name");
var bits = file.Optional<byte[]>("bits");
var directoryName = Path.GetDirectoryName(name);
var filePath = _mediaFileStore.Combine(directoryName, Path.GetFileName(name));
Stream stream = null;
try
{
stream = new MemoryStream(bits);
filePath = await _mediaFileStore.CreateFileFromStreamAsync(filePath, stream);
}
finally
{
stream?.Dispose();
}
var publicUrl = _mediaFileStore.MapPathToPublicUrl(filePath);
return new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well.
.Set("file", publicUrl)
.Set("url", publicUrl)
.Set("type", file.Optional<string>("type"));
}
private async Task<XRpcArray> MetaWeblogGetUserBlogsAsync(XmlRpcContext context, string userName, string password)
{
var user = await ValidateUserAsync(userName, password);
XRpcArray array = new XRpcArray();
// Look for all types using ListPart
foreach (var type in _contentDefinitionManager.ListTypeDefinitions())
{
if (!type.Parts.Any(x => x.Name == nameof(ListPart)))
{
continue;
}
foreach (var list in await _session.Query<ContentItem, ContentItemIndex>(x => x.ContentType == type.Name).ListAsync())
{
// User needs to at least have permission to edit its own blog posts to access the service
if (await _authorizationService.AuthorizeAsync(user, CommonPermissions.EditContent, list))
{
var metadata = await _contentManager.PopulateAspectAsync<ContentItemMetadata>(list);
var displayRouteValues = metadata.DisplayRouteValues;
array.Add(new XRpcStruct()
.Set("url", context.Url.Action(displayRouteValues["action"].ToString(), displayRouteValues["controller"].ToString(), displayRouteValues, context.HttpContext.Request.Scheme))
.Set("blogid", list.ContentItemId)
.Set("blogName", list.DisplayText));
}
}
}
return array;
}
private async Task<XRpcArray> MetaWeblogGetRecentPosts(
XmlRpcContext context,
string contentItemId,
string userName,
string password,
int numberOfPosts,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
// User needs to at least have permission to edit its own blog posts to access the service
await CheckAccessAsync(CommonPermissions.EditContent, user, null);
var list = await _contentManager.GetAsync(contentItemId);
if (list == null)
{
throw new InvalidOperationException("Could not find content item " + contentItemId);
}
var array = new XRpcArray();
var contentItems = await _session.Query<ContentItem>()
.With<ContainedPartIndex>(x => x.ListContentItemId == contentItemId)
.With<ContentItemIndex>(x => x.Latest)
.OrderByDescending(x => x.CreatedUtc)
.Take(numberOfPosts)
.ListAsync();
foreach (var contentItem in contentItems)
{
var postStruct = await CreateBlogStructAsync(context, contentItem);
foreach (var driver in drivers)
{
driver.Process(postStruct);
}
array.Add(postStruct);
}
return array;
}
private async Task<string> MetaWeblogNewPostAsync(
string contentItemId,
string userName,
string password,
XRpcStruct content,
bool publish,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
// User needs permission to edit or publish its own blog posts
await CheckAccessAsync(publish ? CommonPermissions.PublishContent : CommonPermissions.EditContent, user, null);
var list = await _contentManager.GetAsync(contentItemId);
if (list == null)
{
throw new InvalidOperationException("Could not find content item " + contentItemId);
}
var postType = GetContainedContentTypes(list).FirstOrDefault();
var contentItem = await _contentManager.NewAsync(postType.Name);
contentItem.Owner = userName;
contentItem.Alter<ContainedPart>(x => x.ListContentItemId = list.ContentItemId);
foreach (var driver in _metaWeblogDrivers)
{
driver.EditPost(content, contentItem);
}
await _contentManager.CreateAsync(contentItem, VersionOptions.Draft);
// try to get the UTC time zone by default
var publishedUtc = content.Optional<DateTime?>("date_created_gmt");
if (publishedUtc == null)
{
// take the local one
publishedUtc = content.Optional<DateTime?>("dateCreated");
}
else
{
// ensure it's read as a UTC time
publishedUtc = new DateTime(publishedUtc.Value.Ticks, DateTimeKind.Utc);
}
if (publish && (publishedUtc == null || publishedUtc <= DateTime.UtcNow))
{
await _contentManager.PublishAsync(contentItem);
}
else
{
await _contentManager.SaveDraftAsync(contentItem);
}
if (publishedUtc != null)
{
contentItem.CreatedUtc = publishedUtc;
}
foreach (var driver in drivers)
{
driver.Process(contentItem.ContentItemId);
}
return contentItem.ContentItemId;
}
private async Task<XRpcStruct> MetaWeblogGetPostAsync(
XmlRpcContext context,
string contentItemId,
string userName,
string password,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
throw new ArgumentException();
}
await CheckAccessAsync(CommonPermissions.EditContent, user, contentItem);
var postStruct = await CreateBlogStructAsync(context, contentItem);
foreach (var driver in _metaWeblogDrivers)
{
driver.BuildPost(postStruct, context, contentItem);
}
foreach (var driver in drivers)
{
driver.Process(postStruct);
}
return postStruct;
}
private async Task<bool> MetaWeblogEditPostAsync(
string contentItemId,
string userName,
string password,
XRpcStruct content,
bool publish,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.DraftRequired);
if (contentItem == null)
{
throw new Exception(S["The specified Blog Post doesn't exist anymore. Please create a new Blog Post."]);
}
await CheckAccessAsync(publish ? CommonPermissions.PublishContent : CommonPermissions.EditContent, user, contentItem);
foreach (var driver in _metaWeblogDrivers)
{
driver.EditPost(content, contentItem);
}
// try to get the UTC time zone by default
var publishedUtc = content.Optional<DateTime?>("date_created_gmt");
if (publishedUtc == null)
{
// take the local one
publishedUtc = content.Optional<DateTime?>("dateCreated");
}
else
{
// ensure it's read as a UTC time
publishedUtc = new DateTime(publishedUtc.Value.Ticks, DateTimeKind.Utc);
}
if (publish && (publishedUtc == null || publishedUtc <= DateTime.UtcNow))
{
await _contentManager.PublishAsync(contentItem);
}
else
{
await _contentManager.SaveDraftAsync(contentItem);
}
if (publishedUtc != null)
{
contentItem.CreatedUtc = publishedUtc;
}
foreach (var driver in drivers)
{
driver.Process(contentItem.Id);
}
return true;
}
private async Task<bool> MetaWeblogDeletePostAsync(
string contentItemId,
string userName,
string password,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
throw new ArgumentException();
}
if (!await _authorizationService.AuthorizeAsync(user, CommonPermissions.DeleteContent, contentItem))
{
throw new InvalidOperationException(S["Not authorized to delete this content"].Value);
}
foreach (var driver in drivers)
{
driver.Process(contentItem.ContentItemId);
}
await _contentManager.RemoveAsync(contentItem);
return true;
}
private async Task<ClaimsPrincipal> ValidateUserAsync(string userName, string password)
{
if (!await _membershipService.CheckPasswordAsync(userName, password))
{
throw new InvalidOperationException(S["The username or e-mail or password provided is incorrect."].Value);
}
var storeUser = await _membershipService.GetUserAsync(userName);
if (storeUser == null)
{
return null;
}
return await _membershipService.CreateClaimsPrincipal(storeUser);
}
private async Task<XRpcStruct> CreateBlogStructAsync(XmlRpcContext context, ContentItem contentItem)
{
var metadata = await _contentManager.PopulateAspectAsync<ContentItemMetadata>(contentItem);
var url = context.Url.Action(
metadata.DisplayRouteValues["action"].ToString(),
metadata.DisplayRouteValues["controller"].ToString(),
metadata.DisplayRouteValues,
context.HttpContext.Request.Scheme);
if (contentItem.HasDraft())
{
url = context.Url.Action("Preview", "Item", new { area = "OrchardCore.Contents", contentItemId = contentItem.ContentItemId });
}
var blogStruct = new XRpcStruct()
.Set("postid", contentItem.ContentItemId)
.Set("link", url)
.Set("permaLink", url);
if (contentItem.PublishedUtc != null)
{
blogStruct.Set("dateCreated", contentItem.PublishedUtc);
blogStruct.Set("date_created_gmt", contentItem.PublishedUtc);
}
foreach (var driver in _metaWeblogDrivers)
{
driver.BuildPost(blogStruct, context, contentItem);
}
return blogStruct;
}
private async Task CheckAccessAsync(Permission permission, ClaimsPrincipal user, ContentItem contentItem)
{
if (!await _authorizationService.AuthorizeAsync(user, permission, contentItem))
{
throw new InvalidOperationException(S["Not authorized to delete this content"].Value);
}
}
private IEnumerable<ContentTypeDefinition> GetContainedContentTypes(ContentItem contentItem)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "ListPart"));
var settings = contentTypePartDefinition.GetSettings<ListPartSettings>();
var contentTypes = settings.ContainedContentTypes ?? Enumerable.Empty<string>();
return contentTypes.Select(contentType => _contentDefinitionManager.GetTypeDefinition(contentType));
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// 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 ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
using System;
namespace ComponentAce.Compression.Libs.zlib
{
sealed public class ZStream
{
private const int MAX_WBITS = 15; // 32K LZ77 window
private static readonly int DEF_WBITS = MAX_WBITS;
private const int Z_NO_FLUSH = 0;
private const int Z_PARTIAL_FLUSH = 1;
private const int Z_SYNC_FLUSH = 2;
private const int Z_FULL_FLUSH = 3;
private const int Z_FINISH = 4;
private const int MAX_MEM_LEVEL = 9;
private const int Z_OK = 0;
private const int Z_STREAM_END = 1;
private const int Z_NEED_DICT = 2;
private const int Z_ERRNO = - 1;
private const int Z_STREAM_ERROR = - 2;
private const int Z_DATA_ERROR = - 3;
private const int Z_MEM_ERROR = - 4;
private const int Z_BUF_ERROR = - 5;
private const int Z_VERSION_ERROR = - 6;
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public System.String msg;
internal Deflate dstate;
internal Inflate istate;
internal int data_type; // best guess about the data type: ascii or binary
public long adler;
internal Adler32 _adler = new Adler32();
public int inflateInit()
{
return inflateInit(DEF_WBITS);
}
public int inflateInit(int w)
{
istate = new Inflate();
return istate.inflateInit(this, w);
}
public int inflate(int f)
{
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflate(this, f);
}
public int inflateEnd()
{
if (istate == null)
return Z_STREAM_ERROR;
int ret = istate.inflateEnd(this);
istate = null;
return ret;
}
public int inflateSync()
{
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync(this);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength)
{
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int deflateInit(int level)
{
return deflateInit(level, MAX_WBITS);
}
public int deflateInit(int level, int bits)
{
dstate = new Deflate();
return dstate.deflateInit(this, level, bits);
}
public int deflate(int flush)
{
if (dstate == null)
{
return Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd()
{
if (dstate == null)
return Z_STREAM_ERROR;
int ret = dstate.deflateEnd();
dstate = null;
return ret;
}
public int deflateParams(int level, int strategy)
{
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary(byte[] dictionary, int dictLength)
{
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(this, dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
internal void flush_pending()
{
int len = dstate.pending;
if (len > avail_out)
len = avail_out;
if (len == 0)
return ;
if (dstate.pending_buf.Length <= dstate.pending_out || next_out.Length <= next_out_index || dstate.pending_buf.Length < (dstate.pending_out + len) || next_out.Length < (next_out_index + len))
{
//System.Console.Out.WriteLine(dstate.pending_buf.Length + ", " + dstate.pending_out + ", " + next_out.Length + ", " + next_out_index + ", " + len);
//System.Console.Out.WriteLine("avail_out=" + avail_out);
}
Array.Copy(dstate.pending_buf, dstate.pending_out, next_out, next_out_index, len);
next_out_index += len;
dstate.pending_out += len;
total_out += len;
avail_out -= len;
dstate.pending -= len;
if (dstate.pending == 0)
{
dstate.pending_out = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
internal int read_buf(byte[] buf, int start, int size)
{
int len = avail_in;
if (len > size)
len = size;
if (len == 0)
return 0;
avail_in -= len;
if (dstate.noheader == 0)
{
adler = _adler.adler32(adler, next_in, next_in_index, len);
}
Array.Copy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
public void free()
{
next_in = null;
next_out = null;
msg = null;
_adler = null;
}
}
}
| |
namespace PTWin
{
partial class ProjectEdit
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.Label DescriptionLabel;
System.Windows.Forms.Label EndedLabel;
System.Windows.Forms.Label IdLabel;
System.Windows.Forms.Label NameLabel;
System.Windows.Forms.Label StartedLabel;
this.CloseButton = new System.Windows.Forms.Button();
this.ApplyButton = new System.Windows.Forms.Button();
this.Cancel_Button = new System.Windows.Forms.Button();
this.OKButton = new System.Windows.Forms.Button();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.UnassignButton = new System.Windows.Forms.Button();
this.AssignButton = new System.Windows.Forms.Button();
this.ResourcesDataGridView = new System.Windows.Forms.DataGridView();
this.ResourceId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.FullName = new System.Windows.Forms.DataGridViewLinkColumn();
this.Role = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.roleListBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.assignedDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.resourcesBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.projectBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.DescriptionTextBox = new System.Windows.Forms.TextBox();
this.EndedTextBox = new System.Windows.Forms.TextBox();
this.IdLabel1 = new System.Windows.Forms.Label();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.StartedTextBox = new System.Windows.Forms.TextBox();
this.ErrorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
this.ReadWriteAuthorization1 = new Csla.Windows.ReadWriteAuthorization(this.components);
this.bindingSourceRefresh1 = new Csla.Windows.BindingSourceRefresh(this.components);
DescriptionLabel = new System.Windows.Forms.Label();
EndedLabel = new System.Windows.Forms.Label();
IdLabel = new System.Windows.Forms.Label();
NameLabel = new System.Windows.Forms.Label();
StartedLabel = new System.Windows.Forms.Label();
this.GroupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ResourcesDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.roleListBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.resourcesBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.projectBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).BeginInit();
this.SuspendLayout();
//
// DescriptionLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(DescriptionLabel, false);
DescriptionLabel.AutoSize = true;
DescriptionLabel.Location = new System.Drawing.Point(12, 120);
DescriptionLabel.Name = "DescriptionLabel";
DescriptionLabel.Size = new System.Drawing.Size(63, 13);
DescriptionLabel.TabIndex = 8;
DescriptionLabel.Text = "Description:";
//
// EndedLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(EndedLabel, false);
EndedLabel.AutoSize = true;
EndedLabel.Location = new System.Drawing.Point(12, 94);
EndedLabel.Name = "EndedLabel";
EndedLabel.Size = new System.Drawing.Size(41, 13);
EndedLabel.TabIndex = 6;
EndedLabel.Text = "Ended:";
//
// IdLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(IdLabel, false);
IdLabel.AutoSize = true;
IdLabel.Location = new System.Drawing.Point(12, 13);
IdLabel.Name = "IdLabel";
IdLabel.Size = new System.Drawing.Size(19, 13);
IdLabel.TabIndex = 0;
IdLabel.Text = "Id:";
//
// NameLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(NameLabel, false);
NameLabel.AutoSize = true;
NameLabel.Location = new System.Drawing.Point(12, 42);
NameLabel.Name = "NameLabel";
NameLabel.Size = new System.Drawing.Size(38, 13);
NameLabel.TabIndex = 2;
NameLabel.Text = "Name:";
//
// StartedLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(StartedLabel, false);
StartedLabel.AutoSize = true;
StartedLabel.Location = new System.Drawing.Point(12, 68);
StartedLabel.Name = "StartedLabel";
StartedLabel.Size = new System.Drawing.Size(44, 13);
StartedLabel.TabIndex = 4;
StartedLabel.Text = "Started:";
//
// CloseButton
//
this.CloseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.CloseButton, false);
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Location = new System.Drawing.Point(578, 100);
this.CloseButton.Name = "CloseButton";
this.CloseButton.Size = new System.Drawing.Size(75, 23);
this.CloseButton.TabIndex = 14;
this.CloseButton.Text = "Close";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// ApplyButton
//
this.ApplyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.ApplyButton, false);
this.ApplyButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ApplyButton.Location = new System.Drawing.Point(578, 42);
this.ApplyButton.Name = "ApplyButton";
this.ApplyButton.Size = new System.Drawing.Size(75, 23);
this.ApplyButton.TabIndex = 12;
this.ApplyButton.Text = "Apply";
this.ApplyButton.UseVisualStyleBackColor = true;
this.ApplyButton.Click += new System.EventHandler(this.ApplyButton_Click);
//
// Cancel_Button
//
this.Cancel_Button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.Cancel_Button, false);
this.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Cancel_Button.Location = new System.Drawing.Point(578, 71);
this.Cancel_Button.Name = "Cancel_Button";
this.Cancel_Button.Size = new System.Drawing.Size(75, 23);
this.Cancel_Button.TabIndex = 13;
this.Cancel_Button.Text = "Cancel";
this.Cancel_Button.UseVisualStyleBackColor = true;
this.Cancel_Button.Click += new System.EventHandler(this.Cancel_Button_Click);
//
// OKButton
//
this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.OKButton, false);
this.OKButton.Location = new System.Drawing.Point(578, 13);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 23);
this.OKButton.TabIndex = 11;
this.OKButton.Text = "OK";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// GroupBox1
//
this.GroupBox1.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.ReadWriteAuthorization1.SetApplyAuthorization(this.GroupBox1, false);
this.GroupBox1.Controls.Add(this.UnassignButton);
this.GroupBox1.Controls.Add(this.AssignButton);
this.GroupBox1.Controls.Add(this.ResourcesDataGridView);
this.GroupBox1.Location = new System.Drawing.Point(81, 231);
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.Size = new System.Drawing.Size(460, 210);
this.GroupBox1.TabIndex = 10;
this.GroupBox1.TabStop = false;
this.GroupBox1.Text = "Resources";
//
// UnassignButton
//
this.UnassignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.UnassignButton, false);
this.UnassignButton.Location = new System.Drawing.Point(379, 48);
this.UnassignButton.Name = "UnassignButton";
this.UnassignButton.Size = new System.Drawing.Size(75, 23);
this.UnassignButton.TabIndex = 2;
this.UnassignButton.Text = "Unassign";
this.UnassignButton.UseVisualStyleBackColor = true;
this.UnassignButton.Click += new System.EventHandler(this.UnassignButton_Click);
//
// AssignButton
//
this.AssignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignButton, false);
this.AssignButton.Location = new System.Drawing.Point(379, 19);
this.AssignButton.Name = "AssignButton";
this.AssignButton.Size = new System.Drawing.Size(75, 23);
this.AssignButton.TabIndex = 1;
this.AssignButton.Text = "Assign";
this.AssignButton.UseVisualStyleBackColor = true;
this.AssignButton.Click += new System.EventHandler(this.AssignButton_Click);
//
// ResourcesDataGridView
//
this.ResourcesDataGridView.AllowUserToAddRows = false;
this.ResourcesDataGridView.AllowUserToDeleteRows = false;
this.ResourcesDataGridView.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.ReadWriteAuthorization1.SetApplyAuthorization(this.ResourcesDataGridView, false);
this.ResourcesDataGridView.AutoGenerateColumns = false;
this.ResourcesDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.ResourcesDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ResourceId,
this.FullName,
this.Role,
this.assignedDataGridViewTextBoxColumn});
this.ResourcesDataGridView.DataSource = this.resourcesBindingSource;
this.ResourcesDataGridView.Location = new System.Drawing.Point(6, 19);
this.ResourcesDataGridView.MultiSelect = false;
this.ResourcesDataGridView.Name = "ResourcesDataGridView";
this.ResourcesDataGridView.RowHeadersVisible = false;
this.ResourcesDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.ResourcesDataGridView.Size = new System.Drawing.Size(367, 185);
this.ResourcesDataGridView.TabIndex = 0;
this.ResourcesDataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResourcesDataGridView_CellContentClick);
//
// ResourceId
//
this.ResourceId.DataPropertyName = "ResourceId";
this.ResourceId.HeaderText = "ResourceId";
this.ResourceId.Name = "ResourceId";
this.ResourceId.ReadOnly = true;
this.ResourceId.Visible = false;
this.ResourceId.Width = 87;
//
// FullName
//
this.FullName.DataPropertyName = "FullName";
this.FullName.HeaderText = "FullName";
this.FullName.Name = "FullName";
this.FullName.ReadOnly = true;
this.FullName.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.FullName.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.FullName.Width = 76;
//
// Role
//
this.Role.DataPropertyName = "Role";
this.Role.DataSource = this.roleListBindingSource;
this.Role.DisplayMember = "Value";
this.Role.HeaderText = "Role";
this.Role.Name = "Role";
this.Role.ValueMember = "Key";
this.Role.Width = 35;
//
// roleListBindingSource
//
this.roleListBindingSource.DataSource = typeof(ProjectTracker.Library.RoleList);
//
// assignedDataGridViewTextBoxColumn
//
this.assignedDataGridViewTextBoxColumn.DataPropertyName = "Assigned";
this.assignedDataGridViewTextBoxColumn.HeaderText = "Assigned";
this.assignedDataGridViewTextBoxColumn.Name = "assignedDataGridViewTextBoxColumn";
this.assignedDataGridViewTextBoxColumn.ReadOnly = true;
this.assignedDataGridViewTextBoxColumn.Width = 75;
//
// resourcesBindingSource
//
this.resourcesBindingSource.DataMember = "Resources";
this.resourcesBindingSource.DataSource = this.projectBindingSource;
this.bindingSourceRefresh1.SetReadValuesOnChange(this.resourcesBindingSource, false);
//
// projectBindingSource
//
this.projectBindingSource.DataSource = typeof(ProjectTracker.Library.ProjectEdit);
this.bindingSourceRefresh1.SetReadValuesOnChange(this.projectBindingSource, true);
//
// DescriptionTextBox
//
this.DescriptionTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.DescriptionTextBox, true);
this.DescriptionTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.projectBindingSource, "Description", true));
this.DescriptionTextBox.Location = new System.Drawing.Point(81, 117);
this.DescriptionTextBox.Multiline = true;
this.DescriptionTextBox.Name = "DescriptionTextBox";
this.DescriptionTextBox.Size = new System.Drawing.Size(460, 108);
this.DescriptionTextBox.TabIndex = 9;
//
// EndedTextBox
//
this.EndedTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.EndedTextBox, true);
this.EndedTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.projectBindingSource, "Ended", true));
this.EndedTextBox.Location = new System.Drawing.Point(81, 91);
this.EndedTextBox.Name = "EndedTextBox";
this.EndedTextBox.Size = new System.Drawing.Size(460, 20);
this.EndedTextBox.TabIndex = 7;
//
// IdLabel1
//
this.IdLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.IdLabel1, false);
this.IdLabel1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.projectBindingSource, "Id", true));
this.IdLabel1.Location = new System.Drawing.Point(81, 13);
this.IdLabel1.Name = "IdLabel1";
this.IdLabel1.Size = new System.Drawing.Size(460, 23);
this.IdLabel1.TabIndex = 1;
//
// NameTextBox
//
this.NameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.NameTextBox, true);
this.NameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.projectBindingSource, "Name", true));
this.NameTextBox.Location = new System.Drawing.Point(81, 39);
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.Size = new System.Drawing.Size(460, 20);
this.NameTextBox.TabIndex = 3;
//
// StartedTextBox
//
this.StartedTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.StartedTextBox, true);
this.StartedTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.projectBindingSource, "Started", true));
this.StartedTextBox.Location = new System.Drawing.Point(81, 65);
this.StartedTextBox.Name = "StartedTextBox";
this.StartedTextBox.Size = new System.Drawing.Size(460, 20);
this.StartedTextBox.TabIndex = 5;
//
// ErrorProvider1
//
this.ErrorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.ErrorProvider1.ContainerControl = this;
this.ErrorProvider1.DataSource = this.projectBindingSource;
//
// bindingSourceRefresh1
//
this.bindingSourceRefresh1.Host = this;
//
// ProjectEdit
//
this.ReadWriteAuthorization1.SetApplyAuthorization(this, false);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.ApplyButton);
this.Controls.Add(this.Cancel_Button);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.GroupBox1);
this.Controls.Add(DescriptionLabel);
this.Controls.Add(this.DescriptionTextBox);
this.Controls.Add(EndedLabel);
this.Controls.Add(IdLabel);
this.Controls.Add(NameLabel);
this.Controls.Add(StartedLabel);
this.Controls.Add(this.EndedTextBox);
this.Controls.Add(this.IdLabel1);
this.Controls.Add(this.NameTextBox);
this.Controls.Add(this.StartedTextBox);
this.Name = "ProjectEdit";
this.Size = new System.Drawing.Size(665, 454);
this.Load += new System.EventHandler(this.ProjectEdit_Load);
this.CurrentPrincipalChanged += new System.EventHandler(this.ProjectEdit_CurrentPrincipalChanged);
this.GroupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ResourcesDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.roleListBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.resourcesBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.projectBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.Button CloseButton;
internal System.Windows.Forms.Button ApplyButton;
internal System.Windows.Forms.Button Cancel_Button;
internal System.Windows.Forms.Button OKButton;
internal System.Windows.Forms.GroupBox GroupBox1;
internal System.Windows.Forms.Button UnassignButton;
internal System.Windows.Forms.Button AssignButton;
internal System.Windows.Forms.DataGridView ResourcesDataGridView;
internal System.Windows.Forms.TextBox DescriptionTextBox;
internal System.Windows.Forms.TextBox EndedTextBox;
internal System.Windows.Forms.Label IdLabel1;
internal System.Windows.Forms.TextBox NameTextBox;
internal System.Windows.Forms.TextBox StartedTextBox;
internal Csla.Windows.ReadWriteAuthorization ReadWriteAuthorization1;
internal System.Windows.Forms.ErrorProvider ErrorProvider1;
internal System.Windows.Forms.BindingSource projectBindingSource;
internal System.Windows.Forms.BindingSource resourcesBindingSource;
internal System.Windows.Forms.BindingSource roleListBindingSource;
private System.Windows.Forms.DataGridViewTextBoxColumn ResourceId;
private System.Windows.Forms.DataGridViewLinkColumn FullName;
private System.Windows.Forms.DataGridViewComboBoxColumn Role;
private System.Windows.Forms.DataGridViewTextBoxColumn assignedDataGridViewTextBoxColumn;
private Csla.Windows.BindingSourceRefresh bindingSourceRefresh1;
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.Expressions;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
public interface IStep
{
IExpressionNode Condition { get; set; }
bool ContinueOnError { get; }
string DisplayName { get; }
bool Enabled { get; }
IExecutionContext ExecutionContext { get; set; }
TimeSpan? Timeout { get; }
Task RunAsync();
}
[ServiceLocator(Default = typeof(StepsRunner))]
public interface IStepsRunner : IAgentService
{
Task RunAsync(IExecutionContext Context, IList<IStep> steps);
}
public sealed class StepsRunner : AgentService, IStepsRunner
{
// StepsRunner should never throw exception to caller
public async Task RunAsync(IExecutionContext jobContext, IList<IStep> steps)
{
ArgUtil.NotNull(jobContext, nameof(jobContext));
ArgUtil.NotNull(steps, nameof(steps));
// TaskResult:
// Abandoned (Server set this.)
// Canceled
// Failed
// Skipped
// Succeeded
// SucceededWithIssues
CancellationTokenRegistration? jobCancelRegister = null;
jobContext.Variables.Agent_JobStatus = jobContext.Result ?? TaskResult.Succeeded;
foreach (IStep step in steps)
{
Trace.Info($"Processing step: DisplayName='{step.DisplayName}', ContinueOnError={step.ContinueOnError}, Enabled={step.Enabled}");
ArgUtil.Equal(true, step.Enabled, nameof(step.Enabled));
ArgUtil.NotNull(step.ExecutionContext, nameof(step.ExecutionContext));
ArgUtil.NotNull(step.ExecutionContext.Variables, nameof(step.ExecutionContext.Variables));
// Start.
step.ExecutionContext.Start();
// Variable expansion.
List<string> expansionWarnings;
step.ExecutionContext.Variables.RecalculateExpanded(out expansionWarnings);
expansionWarnings?.ForEach(x => step.ExecutionContext.Warning(x));
var expressionManager = HostContext.GetService<IExpressionManager>();
try
{
// Register job cancellation call back only if job cancellation token not been fire before each step run
if (!jobContext.CancellationToken.IsCancellationRequested)
{
// Test the condition again. The job was canceled after the condition was originally evaluated.
jobCancelRegister = jobContext.CancellationToken.Register(() =>
{
// mark job as cancelled
jobContext.Result = TaskResult.Canceled;
jobContext.Variables.Agent_JobStatus = jobContext.Result;
step.ExecutionContext.Debug($"Re-evaluate condition on job cancellation for step: '{step.DisplayName}'.");
ConditionResult conditionReTestResult;
if (HostContext.AgentShutdownToken.IsCancellationRequested)
{
step.ExecutionContext.Debug($"Skip Re-evaluate condition on agent shutdown.");
conditionReTestResult = false;
}
else
{
try
{
conditionReTestResult = expressionManager.Evaluate(step.ExecutionContext, step.Condition, hostTracingOnly: true);
}
catch (Exception ex)
{
// Cancel the step since we get exception while re-evaluate step condition.
Trace.Info("Caught exception from expression when re-test condition on job cancellation.");
step.ExecutionContext.Error(ex);
conditionReTestResult = false;
}
}
if (!conditionReTestResult.Value)
{
// Cancel the step.
Trace.Info("Cancel current running step.");
step.ExecutionContext.CancelToken();
}
});
}
else
{
if (jobContext.Result != TaskResult.Canceled)
{
// mark job as cancelled
jobContext.Result = TaskResult.Canceled;
jobContext.Variables.Agent_JobStatus = jobContext.Result;
}
}
// Evaluate condition.
step.ExecutionContext.Debug($"Evaluating condition for step: '{step.DisplayName}'");
Exception conditionEvaluateError = null;
ConditionResult conditionResult;
if (HostContext.AgentShutdownToken.IsCancellationRequested)
{
step.ExecutionContext.Debug($"Skip evaluate condition on agent shutdown.");
conditionResult = false;
}
else
{
try
{
conditionResult = expressionManager.Evaluate(step.ExecutionContext, step.Condition);
}
catch (Exception ex)
{
Trace.Info("Caught exception from expression.");
Trace.Error(ex);
conditionResult = false;
conditionEvaluateError = ex;
}
}
// no evaluate error but condition is false
if (!conditionResult.Value && conditionEvaluateError == null)
{
// Condition == false
Trace.Info("Skipping step due to condition evaluation.");
step.ExecutionContext.Complete(TaskResult.Skipped, resultCode: conditionResult.Trace);
continue;
}
if (conditionEvaluateError != null)
{
// fail the step since there is an evaluate error.
step.ExecutionContext.Error(conditionEvaluateError);
step.ExecutionContext.Complete(TaskResult.Failed);
}
else
{
// Run the step.
await RunStepAsync(step, jobContext.CancellationToken);
}
}
finally
{
if (jobCancelRegister != null)
{
jobCancelRegister?.Dispose();
jobCancelRegister = null;
}
}
// Update the job result.
if (step.ExecutionContext.Result == TaskResult.SucceededWithIssues ||
step.ExecutionContext.Result == TaskResult.Failed)
{
Trace.Info($"Update job result with current step result '{step.ExecutionContext.Result}'.");
jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, step.ExecutionContext.Result.Value);
jobContext.Variables.Agent_JobStatus = jobContext.Result;
}
else
{
Trace.Info($"No need for updating job result with current step result '{step.ExecutionContext.Result}'.");
}
Trace.Info($"Current state: job state = '{jobContext.Result}'");
}
}
private async Task RunStepAsync(IStep step, CancellationToken jobCancellationToken)
{
// Start the step.
Trace.Info("Starting the step.");
step.ExecutionContext.Section(StringUtil.Loc("StepStarting", step.DisplayName));
step.ExecutionContext.SetTimeout(timeout: step.Timeout);
try
{
await step.RunAsync();
}
catch (OperationCanceledException ex)
{
if (step.ExecutionContext.CancellationToken.IsCancellationRequested &&
!jobCancellationToken.IsCancellationRequested)
{
Trace.Error($"Caught timeout exception from step: {ex.Message}");
step.ExecutionContext.Error(StringUtil.Loc("StepTimedOut"));
step.ExecutionContext.Result = TaskResult.Failed;
}
else
{
// Log the exception and cancel the step.
Trace.Error($"Caught cancellation exception from step: {ex}");
step.ExecutionContext.Error(ex);
step.ExecutionContext.Result = TaskResult.Canceled;
}
}
catch (Exception ex)
{
// Log the error and fail the step.
Trace.Error($"Caught exception from step: {ex}");
step.ExecutionContext.Error(ex);
step.ExecutionContext.Result = TaskResult.Failed;
}
// Wait till all async commands finish.
foreach (var command in step.ExecutionContext.AsyncCommands ?? new List<IAsyncCommandContext>())
{
try
{
// wait async command to finish.
await command.WaitAsync();
}
catch (OperationCanceledException ex)
{
if (step.ExecutionContext.CancellationToken.IsCancellationRequested &&
!jobCancellationToken.IsCancellationRequested)
{
// Log the timeout error, set step result to falied if the current result is not canceled.
Trace.Error($"Caught timeout exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(StringUtil.Loc("StepTimedOut"));
// if the step already canceled, don't set it to failed.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Failed);
}
else
{
// log and save the OperationCanceledException, set step result to canceled if the current result is not failed.
Trace.Error($"Caught cancellation exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(ex);
// if the step already failed, don't set it to canceled.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Canceled);
}
}
catch (Exception ex)
{
// Log the error, set step result to falied if the current result is not canceled.
Trace.Error($"Caught exception from async command {command.Name}: {ex}");
step.ExecutionContext.Error(ex);
// if the step already canceled, don't set it to failed.
step.ExecutionContext.CommandResult = TaskResultUtil.MergeTaskResults(step.ExecutionContext.CommandResult, TaskResult.Failed);
}
}
// Merge executioncontext result with command result
if (step.ExecutionContext.CommandResult != null)
{
step.ExecutionContext.Result = TaskResultUtil.MergeTaskResults(step.ExecutionContext.Result, step.ExecutionContext.CommandResult.Value);
}
// Fixup the step result if ContinueOnError.
if (step.ExecutionContext.Result == TaskResult.Failed && step.ContinueOnError)
{
step.ExecutionContext.Result = TaskResult.SucceededWithIssues;
Trace.Info($"Updated step result: {step.ExecutionContext.Result}");
}
else
{
Trace.Info($"Step result: {step.ExecutionContext.Result}");
}
// Complete the step context.
step.ExecutionContext.Section(StringUtil.Loc("StepFinishing", step.DisplayName));
step.ExecutionContext.Complete();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
namespace Player
{
#region classes
class Point
{
public int X { get; set; }
public int Y { get; set; }
}
class Drone
{
public Drone(int zoneCount, int droneId)
{
TargetZones = new List<TargetZone>(zoneCount);
Linked = false;
DroneId = droneId;
Wait = 0;
}
public Point Position { get; set; }
public List<TargetZone> TargetZones { get; set; }
public bool Linked { get; set; }
public int LinkNo { get; set; }
public Zone Target { get; set; }
public int DroneId { get; set; }
public double BestDistance { get; set; }
public int DroneClass { get; set; }
public int Wait { get; set; }
}
class TargetZone
{
public Zone Zone { get; set; }
public double Distance { get; set; }
}
class TargetDrone
{
public Drone Drone { get; set; }
public double Distance { get; set; }
}
class LinkedDrones
{
public Drone Dron { get; set; }
public double Distance { get; set; }
}
class Zone
{
public const int Radius = 100;
public Zone(int droneCount)
{
TargetDrone = new List<TargetDrone>(droneCount);
}
public Point Center { get; set; }
public int OwnerId { get; set; } // -1 if no owner
public List<TargetDrone> TargetDrone { get; set; }
public int MaxDrones { get; set; }
public int MaxTreat { get; set; }
public int MyDrones { get; set; }
public int ZoneId { get; set; }
public int ZoneClass { get; set; }
public double BestDistance { get; set; }
}
class Team
{
public Team(int droneCount, int zoneCount, int teamId)
{
Drones = new List<Drone>(droneCount);
TeamId = teamId;
for (var droneId = 0; droneId < droneCount; droneId++)
Drones.Add(new Drone(zoneCount, droneId));
}
public IList<Drone> Drones { get; set; }
public int TeamId { get; set; }
}
#endregion
class Game
{
#region consts
List<Zone> _zones; // all game zones
List<Team> _teams; // all the team of drones. Array index = team's ID
int _myTeamId; // index of my team in the array of teams
public static int LinkId = -1;
public static TargetZone[] LinkedTargetZone = new TargetZone[10000];
public static int ZoneCount = 0;
public static int DroneCount = 0;
#endregion
// read initial games data (one time at the beginning of the game: P I D Z...)
public void Init()
{
var pidz = ReadIntegers();
ZoneCount = pidz[3];
DroneCount = pidz[2];
_myTeamId = pidz[1];
_zones = ReadZones(pidz[3], pidz[2]).ToList();
_teams = ReadTeams(pidz[0], pidz[2], pidz[3]).ToList();
}
IEnumerable<Zone> ReadZones(int zoneCount, int dronesPerTeam)
{
for (var areaId = 0; areaId < zoneCount; areaId++)
yield return new Zone(dronesPerTeam) { Center = ReadPoint(), ZoneId = areaId};
}
IEnumerable<Team> ReadTeams(int teamCount, int dronesPerTeam, int zoneCount)
{
for (var teamId = 0; teamId < teamCount; teamId++)
yield return new Team(dronesPerTeam, zoneCount, teamId);
}
public void ReadContext()
{
foreach (var zone in _zones)
{
zone.OwnerId = ReadIntegers()[0];
}
foreach (var team in _teams)
foreach (var drone in team.Drones)
drone.Position = ReadPoint();
}
// Compute logic here. This method is called for each game round.
public void Play()
{
var myDrones = _teams[_myTeamId].Drones;
#region Zones loop
foreach (var zone in _zones)
{
zone.MaxDrones = 0;
zone.MyDrones = 0;
zone.MaxTreat = 0;
zone.TargetDrone.Clear();
foreach (var team in _teams)
{
int count = team.Drones.Count(a => ProximityDetection(zone.Center, a.Position));
if (count > 0)
{
if (team.TeamId == _myTeamId)
{
zone.MyDrones = count;
}
else
{
zone.MaxDrones = count > zone.MaxDrones ? count : zone.MaxDrones;
}
}
count = team.Drones.Count(a => TreatDetection(zone.Center, a.Position));
if (count > 0)
{
if (team.TeamId != _myTeamId)
{
zone.MaxTreat = count > zone.MaxTreat ? count : zone.MaxTreat;
}
}
}
zone.TargetDrone = new List<TargetDrone>(myDrones.Count());
zone.TargetDrone.AddRange(myDrones.Select(myDrone => new TargetDrone
{
Distance = GetDistance(myDrone.Position.X, myDrone.Position.Y, zone.Center.X, zone.Center.Y),
Drone = myDrone
}));
zone.BestDistance = zone.TargetDrone.OrderBy(o => o.Distance).Select(a => a.Distance).First();
if (zone.OwnerId == _myTeamId && zone.MaxTreat > 0)
{
zone.ZoneClass = 0;
}
else if (zone.OwnerId != _myTeamId && zone.MaxDrones == 0)
{
zone.ZoneClass = 1;
}
else if (zone.OwnerId != _myTeamId && zone.MaxTreat < 2)
{
zone.ZoneClass = 2;
}
else if (zone.OwnerId != _myTeamId && zone.MaxTreat > 1)
{
zone.ZoneClass = 3;
}
else if (zone.OwnerId == _myTeamId && zone.MaxTreat == 0)
{
zone.ZoneClass = 4;
}
}
#endregion
#region drones loop
foreach (var drone in myDrones)
{
drone.TargetZones.Clear();
drone.Target = null;
foreach (var zone in _zones)
{
TargetZone tZ = new TargetZone { Zone = zone, Distance = GetDistance(drone.Position.X, drone.Position.Y, zone.Center.X, zone.Center.Y) };
drone.TargetZones.Add(tZ);
}
if (drone.TargetZones.Count(z => z.Distance < 100 && z.Zone.MaxTreat > 0 && z.Zone.OwnerId == _myTeamId) > 0)
{
drone.DroneClass = 0;
}
else if (drone.TargetZones.Count(z => z.Distance < 300 && z.Zone.OwnerId != _myTeamId) > 0)
{
drone.DroneClass = 1;
}
else
{
drone.DroneClass = 2;
}
}
#endregion
GetTargetZone(_zones, myDrones);
foreach (Drone drone in myDrones)
{
string cords;
if (drone.Target == null)
{
TargetZone tz = drone.TargetZones.OrderBy(o => o.Distance).FirstOrDefault(f => f.Zone.OwnerId == _myTeamId);
if (tz == null)
{
Point wheretogo = GetGravityPoint(_zones);
cords = (wheretogo.X) + " " + (wheretogo.Y);
}
else
{
cords = (tz.Zone.Center.X) + " " + (tz.Zone.Center.Y);
}
}
else
{
cords = (drone.Target.Center.X) + " " + (drone.Target.Center.Y);
}
Console.WriteLine(cords);
}
//debugger part
//foreach (var zone in _zones.OrderBy(z => z.ZoneClass).ThenBy(z => z.BestDistance))
//{
// Console.Error.WriteLine("zona " + zone.ZoneId + " klasa " + zone.ZoneClass);
//}
//Console.Error.WriteLine("===========================");
//foreach (var drone in myDrones)
//{
// Console.Error.WriteLine("dron " + drone.DroneClass);
//}
}
#region helpers
static int[] ReadIntegers()
{
// ReSharper disable once PossibleNullReferenceException
return Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
}
static Point ReadPoint()
{
var xy = ReadIntegers();
return new Point { X = xy[0], Y = xy[1] };
}
static double GetDistance(int dronex, int droney, int zonex, int zoney)
{
int y = zoney - droney;
int x = zonex - dronex;
double dist = Math.Sqrt(x * x + y * y);
return dist;
}
static bool ProximityDetection(Point center, Point position)
{
if (GetDistance(position.X, position.Y, center.X, center.Y) < 100)
{
return true;
}
return false;
}
static bool TreatDetection(Point center, Point position)
{
if (GetDistance(position.X, position.Y, center.X, center.Y) <= 400)
{
return true;
}
return false;
}
private static Point GetGravityPoint(IList<Zone> zones)
{
int x = 0, y = 0;
foreach (Zone zone in zones.OrderByDescending(o=> o.Center.X).Take(3))
{
x = x + zone.Center.X;
y = y + zone.Center.Y;
}
// ReSharper disable once PossibleLossOfFraction
double centx = x/3;
// ReSharper disable once PossibleLossOfFraction
double centy = y/3;
var tocka = new Point {X = (int) Math.Ceiling(centx), Y = (int) Math.Ceiling(centy)};
return tocka;
}
#endregion
#region getTarget
private static void GetTargetZone(IList<Zone> zones, IList<Drone> myDrones)
{
foreach (Zone zone in zones.OrderBy(z => z.ZoneClass).ThenBy(z => z.BestDistance))
{
if (zone.ZoneClass == 0)
{
if (zone.MaxTreat - zone.MyDrones > 0)
{
List<Drone> drones =
zone.TargetDrone.OrderBy(o => o.Distance)
.ThenByDescending(d => d.Drone.DroneClass)
.Where(w => w.Drone.Target == null).Select(s => s.Drone).Take(zone.MaxTreat - zone.MyDrones).ToList();
foreach (Drone drone in drones)
{
drone.Target = zone;
}
}
else
{
List<Drone> drones =
zone.TargetDrone.OrderBy(o => o.Distance)
.ThenByDescending(d => d.Drone.DroneClass)
.Where(w => w.Drone.Target == null).Select(s => s.Drone).Take(zone.MaxTreat).ToList();
foreach (Drone drone in drones)
{
drone.Target = zone;
}
}
}
if (zone.ZoneClass == 1)
{
List<Drone> drones =
zone.TargetDrone.OrderBy(o => o.Distance)
.ThenByDescending(d => d.Drone.DroneClass)
.Where(w => w.Drone.Target == null).Select(s => s.Drone).Take(1).ToList();
foreach (Drone drone in drones)
{
drone.Target = zone;
}
}
if (zone.ZoneClass == 2)
{
List<Drone> drones =
zone.TargetDrone.OrderBy(o => o.Distance)
.ThenByDescending(d => d.Drone.DroneClass)
.Where(w => w.Drone.Target == null).Select(s => s.Drone).Take(zone.MaxDrones+1).ToList();
foreach (Drone drone in drones)
{
drone.Target = zone;
}
}
if (zone.ZoneClass == 3)
{
if (zone.MaxDrones < myDrones.Count(c => c.Target == null) + 1)
{
List<Drone> drones =
zone.TargetDrone.OrderBy(o => o.Distance)
.ThenByDescending(d => d.Drone.DroneClass)
.Where(w => w.Drone.DroneClass > 0 && w.Drone.Target == null).Select(s => s.Drone).Take(zone.MaxDrones + 1).ToList();
foreach (Drone drone in drones)
{
drone.Target = zone;
}
}
}
}
}
#endregion
}
static class Program
{
static void Main()
{
var game = new Game();
game.Init();
while (true)
{
game.ReadContext();
game.Play();
}
// ReSharper disable once FunctionNeverReturns
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Frameworks;
using Xunit;
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAProjectDependenciesCommandResolver
{
private static readonly string s_liveProjectDirectory =
Path.Combine(AppContext.BaseDirectory, "TestAssets/TestProjects/AppWithDirectDependency");
[Fact]
public void It_returns_null_when_CommandName_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = null,
CommandArguments = new string[] { "" },
ProjectDirectory = "/some/directory",
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_ProjectDirectory_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = null,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_Framework_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = null
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_Configuration_is_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = null,
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_CommandName_does_not_exist_in_ProjectDependencies()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "nonexistent-command",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_a_CommandSpec_with_Dotnet_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectDependencies()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileNameWithoutExtension(result.Path);
commandFile.Should().Be("dotnet");
result.Args.Should().Contain(commandResolverArguments.CommandName);
}
[Fact]
public void It_escapes_CommandArguments_when_returning_a_CommandSpec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = new[] { "arg with space" },
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("\"arg with space\"");
}
[Fact]
public void It_passes_depsfile_arg_to_host_when_returning_a_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("--depsfile");
}
[Fact]
public void It_sets_depsfile_in_output_path_in_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var outputDir = Path.Combine(AppContext.BaseDirectory, "outdir");
var commandResolverArguments = new CommandResolverArguments
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10,
OutputPath = outputDir
};
var buildCommand = new BuildCommand(
Path.Combine(s_liveProjectDirectory, "project.json"),
output: outputDir,
framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString())
.Execute().Should().Pass();
var projectContext = ProjectContext.Create(
s_liveProjectDirectory,
FrameworkConstants.CommonFrameworks.NetCoreApp10,
RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());
var depsFilePath =
projectContext.GetOutputPaths("Debug", outputPath: outputDir).RuntimeFiles.DepsJson;
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain($"--depsfile {depsFilePath}");
}
[Fact]
public void It_sets_depsfile_in_build_base_path_in_commandspec()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var buildBasePath = Path.Combine(AppContext.BaseDirectory, "basedir");
var commandResolverArguments = new CommandResolverArguments
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10,
BuildBasePath = buildBasePath
};
var buildCommand = new BuildCommand(
Path.Combine(s_liveProjectDirectory, "project.json"),
buildBasePath: buildBasePath,
framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString())
.Execute().Should().Pass();
var projectContext = ProjectContext.Create(
s_liveProjectDirectory,
FrameworkConstants.CommonFrameworks.NetCoreApp10,
RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());
var depsFilePath =
projectContext.GetOutputPaths("Debug", buildBasePath).RuntimeFiles.DepsJson;
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain($"--depsfile {depsFilePath}");
}
[Fact]
public void It_returns_a_CommandSpec_with_CommandName_in_Args_when_returning_a_CommandSpec_and_CommandArguments_are_null()
{
var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "dotnet-hello",
CommandArguments = null,
ProjectDirectory = s_liveProjectDirectory,
Configuration = "Debug",
Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10
};
var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Contain("dotnet-hello");
}
private ProjectDependenciesCommandResolver SetupProjectDependenciesCommandResolver(
IEnvironmentProvider environment = null,
IPackagedCommandSpecFactory packagedCommandSpecFactory = null)
{
environment = environment ?? new EnvironmentProvider();
packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory();
var projectDependenciesCommandResolver = new ProjectDependenciesCommandResolver(environment, packagedCommandSpecFactory);
return projectDependenciesCommandResolver;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.MessageRoutingSIPRouteBinding", Namespace="urn:iControl")]
public partial class LocalLBMessageRoutingSIPRoute : iControlInterface {
public LocalLBMessageRoutingSIPRoute() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void create(
string [] sip_routes
) {
this.Invoke("create", new object [] {
sip_routes});
}
public System.IAsyncResult Begincreate(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
sip_routes}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_sip_routes
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void delete_all_sip_routes(
) {
this.Invoke("delete_all_sip_routes", new object [0]);
}
public System.IAsyncResult Begindelete_all_sip_routes(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_sip_routes", new object[0], callback, asyncState);
}
public void Enddelete_all_sip_routes(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_sip_route
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void delete_sip_route(
string [] sip_routes
) {
this.Invoke("delete_sip_route", new object [] {
sip_routes});
}
public System.IAsyncResult Begindelete_sip_route(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_sip_route", new object[] {
sip_routes}, callback, asyncState);
}
public void Enddelete_sip_route(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] sip_routes
) {
object [] results = this.Invoke("get_description", new object [] {
sip_routes});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
sip_routes}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_from_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_from_uri(
string [] sip_routes
) {
object [] results = this.Invoke("get_from_uri", new object [] {
sip_routes});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_from_uri(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_from_uri", new object[] {
sip_routes}, callback, asyncState);
}
public string [] Endget_from_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_peer
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_peer(
string [] sip_routes
) {
object [] results = this.Invoke("get_peer", new object [] {
sip_routes});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_peer(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_peer", new object[] {
sip_routes}, callback, asyncState);
}
public string [] [] Endget_peer(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_request_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_request_uri(
string [] sip_routes
) {
object [] results = this.Invoke("get_request_uri", new object [] {
sip_routes});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_request_uri(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_request_uri", new object[] {
sip_routes}, callback, asyncState);
}
public string [] Endget_request_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_selection_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBMessageRoutingSIPRouteSelectionMode [] get_selection_mode(
string [] sip_routes
) {
object [] results = this.Invoke("get_selection_mode", new object [] {
sip_routes});
return ((LocalLBMessageRoutingSIPRouteSelectionMode [])(results[0]));
}
public System.IAsyncResult Beginget_selection_mode(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_selection_mode", new object[] {
sip_routes}, callback, asyncState);
}
public LocalLBMessageRoutingSIPRouteSelectionMode [] Endget_selection_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBMessageRoutingSIPRouteSelectionMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_to_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_to_uri(
string [] sip_routes
) {
object [] results = this.Invoke("get_to_uri", new object [] {
sip_routes});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_to_uri(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_to_uri", new object[] {
sip_routes}, callback, asyncState);
}
public string [] Endget_to_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_virtual_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_virtual_server(
string [] sip_routes
) {
object [] results = this.Invoke("get_virtual_server", new object [] {
sip_routes});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_virtual_server(string [] sip_routes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_virtual_server", new object[] {
sip_routes}, callback, asyncState);
}
public string [] Endget_virtual_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// replace_peer
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void replace_peer(
string [] sip_routes,
string [] [] peers,
long [] [] priorities
) {
this.Invoke("replace_peer", new object [] {
sip_routes,
peers,
priorities});
}
public System.IAsyncResult Beginreplace_peer(string [] sip_routes,string [] [] peers,long [] [] priorities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("replace_peer", new object[] {
sip_routes,
peers,
priorities}, callback, asyncState);
}
public void Endreplace_peer(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_description(
string [] sip_routes,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
sip_routes,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] sip_routes,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
sip_routes,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_from_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_from_uri(
string [] sip_routes,
string [] uris
) {
this.Invoke("set_from_uri", new object [] {
sip_routes,
uris});
}
public System.IAsyncResult Beginset_from_uri(string [] sip_routes,string [] uris, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_from_uri", new object[] {
sip_routes,
uris}, callback, asyncState);
}
public void Endset_from_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_request_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_request_uri(
string [] sip_routes,
string [] uris
) {
this.Invoke("set_request_uri", new object [] {
sip_routes,
uris});
}
public System.IAsyncResult Beginset_request_uri(string [] sip_routes,string [] uris, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_request_uri", new object[] {
sip_routes,
uris}, callback, asyncState);
}
public void Endset_request_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_selection_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_selection_mode(
string [] sip_routes,
LocalLBMessageRoutingSIPRouteSelectionMode [] modes
) {
this.Invoke("set_selection_mode", new object [] {
sip_routes,
modes});
}
public System.IAsyncResult Beginset_selection_mode(string [] sip_routes,LocalLBMessageRoutingSIPRouteSelectionMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_selection_mode", new object[] {
sip_routes,
modes}, callback, asyncState);
}
public void Endset_selection_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_to_uri
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_to_uri(
string [] sip_routes,
string [] uris
) {
this.Invoke("set_to_uri", new object [] {
sip_routes,
uris});
}
public System.IAsyncResult Beginset_to_uri(string [] sip_routes,string [] uris, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_to_uri", new object[] {
sip_routes,
uris}, callback, asyncState);
}
public void Endset_to_uri(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_virtual_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/MessageRoutingSIPRoute",
RequestNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute", ResponseNamespace="urn:iControl:LocalLB/MessageRoutingSIPRoute")]
public void set_virtual_server(
string [] sip_routes,
string [] virtual_servers
) {
this.Invoke("set_virtual_server", new object [] {
sip_routes,
virtual_servers});
}
public System.IAsyncResult Beginset_virtual_server(string [] sip_routes,string [] virtual_servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_virtual_server", new object[] {
sip_routes,
virtual_servers}, callback, asyncState);
}
public void Endset_virtual_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.MessageRoutingSIPRoute.SelectionMode", Namespace = "urn:iControl")]
public enum LocalLBMessageRoutingSIPRouteSelectionMode
{
SELECTION_MODE_UNKNOWN,
SELECTION_MODE_SEQUENTIAL,
SELECTION_MODE_RATIO,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.Xml.Schema;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Configuration;
using System.Xml.Serialization.Configuration;
#if DEBUG
using System.Diagnostics;
#endif
/// <include file='doc\SchemaImporter.uex' path='docs/doc[@for="SchemaImporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class SchemaImporter
{
private XmlSchemas _schemas;
private StructMapping _root;
private CodeGenerationOptions _options;
private TypeScope _scope;
private ImportContext _context;
private bool _rootImported;
private NameTable _typesInUse;
private NameTable _groupsInUse;
internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context)
{
if (!schemas.Contains(XmlSchema.Namespace))
{
schemas.AddReference(XmlSchemas.XsdSchema);
schemas.SchemaSet.Add(XmlSchemas.XsdSchema);
}
if (!schemas.Contains(XmlReservedNs.NsXml))
{
schemas.AddReference(XmlSchemas.XmlSchema);
schemas.SchemaSet.Add(XmlSchemas.XmlSchema);
}
_schemas = schemas;
_options = options;
_context = context;
Schemas.SetCache(Context.Cache, Context.ShareTypes);
}
internal ImportContext Context
{
get
{
if (_context == null)
_context = new ImportContext();
return _context;
}
}
internal Hashtable ImportedElements
{
get { return Context.Elements; }
}
internal Hashtable ImportedMappings
{
get { return Context.Mappings; }
}
internal CodeIdentifiers TypeIdentifiers
{
get { return Context.TypeIdentifiers; }
}
internal XmlSchemas Schemas
{
get
{
if (_schemas == null)
_schemas = new XmlSchemas();
return _schemas;
}
}
internal TypeScope Scope
{
get
{
if (_scope == null)
_scope = new TypeScope();
return _scope;
}
}
internal NameTable GroupsInUse
{
get
{
if (_groupsInUse == null)
_groupsInUse = new NameTable();
return _groupsInUse;
}
}
internal NameTable TypesInUse
{
get
{
if (_typesInUse == null)
_typesInUse = new NameTable();
return _typesInUse;
}
}
internal CodeGenerationOptions Options
{
get { return _options; }
}
internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect)
{
structMapping.ReferencedByTopLevelElement = true;
TypeDesc baseTypeDesc;
if (baseType != null)
{
baseTypeDesc = Scope.GetTypeDesc(baseType);
if (baseTypeDesc != null)
{
TypeDesc typeDescToChange = structMapping.TypeDesc;
if (baseTypeCanBeIndirect)
{
// if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the
// inheritance chain, not necessarily directly to the imported type.
while (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc)
typeDescToChange = typeDescToChange.BaseTypeDesc;
}
if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc)
throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName));
typeDescToChange.BaseTypeDesc = baseTypeDesc;
}
}
}
internal string GenerateUniqueTypeName(string typeName)
{
typeName = CodeIdentifier.MakeValid(typeName);
return TypeIdentifiers.AddUnique(typeName, typeName);
}
private StructMapping CreateRootMapping()
{
TypeDesc typeDesc = Scope.GetTypeDesc(typeof(object));
StructMapping mapping = new StructMapping();
mapping.TypeDesc = typeDesc;
mapping.Members = Array.Empty<MemberMapping>();
mapping.IncludeInSchema = false;
mapping.TypeName = Soap.UrType;
mapping.Namespace = XmlSchema.Namespace;
return mapping;
}
internal StructMapping GetRootMapping()
{
if (_root == null)
_root = CreateRootMapping();
return _root;
}
internal StructMapping ImportRootMapping()
{
if (!_rootImported)
{
_rootImported = true;
ImportDerivedTypes(XmlQualifiedName.Empty);
}
return GetRootMapping();
}
internal abstract void ImportDerivedTypes(XmlQualifiedName baseName);
internal void AddReference(XmlQualifiedName name, NameTable references, string error)
{
if (name.Namespace == XmlSchema.Namespace)
return;
if (references[name] != null)
{
throw new InvalidOperationException(string.Format(error, name.Name, name.Namespace));
}
references[name] = name;
}
internal void RemoveReference(XmlQualifiedName name, NameTable references)
{
references[name] = null;
}
internal void AddReservedIdentifiersForDataBinding(CodeIdentifiers scope)
{
if ((_options & CodeGenerationOptions.EnableDataBinding) != 0)
{
scope.AddReserved("PropertyChanged");
scope.AddReserved("RaisePropertyChanged");
}
}
}
}
| |
// 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;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace System.Net
{
public class WebProxy : IWebProxy, ISerializable
{
private ArrayList _bypassList;
private Regex[] _regExBypassList;
public WebProxy() : this((Uri)null, false, null, null) { }
public WebProxy(Uri Address) : this(Address, false, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
{
this.Address = Address;
this.Credentials = Credentials;
this.BypassProxyOnLocal = BypassOnLocal;
if (BypassList != null)
{
_bypassList = new ArrayList(BypassList);
UpdateRegExList(true);
}
}
public WebProxy(string Host, int Port)
: this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null)
{
}
public WebProxy(string Address)
: this(CreateProxyUri(Address), false, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal)
: this(CreateProxyUri(Address), BypassOnLocal, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
{
}
public Uri Address { get; set; }
public bool BypassProxyOnLocal { get; set; }
public string[] BypassList
{
get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); }
set
{
_bypassList = new ArrayList(value);
UpdateRegExList(true);
}
}
public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList());
public ICredentials Credentials { get; set; }
public bool UseDefaultCredentials
{
get { return Credentials == CredentialCache.DefaultCredentials; }
set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
}
public Uri GetProxy(Uri destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
return IsBypassed(destination) ? destination : Address;
}
private static Uri CreateProxyUri(string address) =>
address == null ? null :
address.IndexOf("://") == -1 ? new Uri("http://" + address) :
new Uri(address);
private void UpdateRegExList(bool canThrow)
{
Regex[] regExBypassList = null;
ArrayList bypassList = _bypassList;
try
{
if (bypassList != null && bypassList.Count > 0)
{
regExBypassList = new Regex[bypassList.Count];
for (int i = 0; i < bypassList.Count; i++)
{
regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
catch
{
if (!canThrow)
{
_regExBypassList = null;
return;
}
throw;
}
// Update field here, as it could throw earlier in the loop
_regExBypassList = regExBypassList;
}
private bool IsMatchInBypassList(Uri input)
{
UpdateRegExList(false);
if (_regExBypassList != null)
{
string matchUriString = input.IsDefaultPort ?
input.Scheme + "://" + input.Host :
input.Scheme + "://" + input.Host + ":" + input.Port.ToString();
foreach (Regex r in _regExBypassList)
{
if (r.IsMatch(matchUriString))
{
return true;
}
}
}
return false;
}
private bool IsLocal(Uri host)
{
string hostString = host.Host;
IPAddress hostAddress;
if (IPAddress.TryParse(hostString, out hostAddress))
{
return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress);
}
// No dot? Local.
int dot = hostString.IndexOf('.');
if (dot == -1)
{
return true;
}
// If it matches the primary domain, it's local. (Whether or not the hostname matches.)
string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName;
return
local.Length == (hostString.Length - dot) &&
string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
private static bool IsAddressLocal(IPAddress ipAddress)
{
// Perf note: The .NET Framework caches this and then uses network change notifications to track
// whether the set should be recomputed. We could consider doing the same if this is observed as
// a bottleneck, but that tracking has its own costs.
IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available
for (int i = 0; i < localAddresses.Length; i++)
{
if (ipAddress.Equals(localAddresses[i]))
{
return true;
}
}
return false;
}
public bool IsBypassed(Uri host)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
return
Address == null ||
host.IsLoopback ||
(BypassProxyOnLocal && IsLocal(host)) ||
IsMatchInBypassList(host);
}
protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
[Obsolete("This method has been deprecated. Please use the proxy selected for you by default. http://go.microsoft.com/fwlink/?linkid=14202")]
public static WebProxy GetDefaultProxy()
{
// The .NET Framework here returns a proxy that fetches IE settings and
// executes JavaScript to determine the correct proxy.
throw new PlatformNotSupportedException();
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Drawing
{
public readonly partial struct Color : System.IEquatable<System.Drawing.Color>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static readonly System.Drawing.Color Empty;
public byte A { get { throw null; } }
public static System.Drawing.Color AliceBlue { get { throw null; } }
public static System.Drawing.Color AntiqueWhite { get { throw null; } }
public static System.Drawing.Color Aqua { get { throw null; } }
public static System.Drawing.Color Aquamarine { get { throw null; } }
public static System.Drawing.Color Azure { get { throw null; } }
public byte B { get { throw null; } }
public static System.Drawing.Color Beige { get { throw null; } }
public static System.Drawing.Color Bisque { get { throw null; } }
public static System.Drawing.Color Black { get { throw null; } }
public static System.Drawing.Color BlanchedAlmond { get { throw null; } }
public static System.Drawing.Color Blue { get { throw null; } }
public static System.Drawing.Color BlueViolet { get { throw null; } }
public static System.Drawing.Color Brown { get { throw null; } }
public static System.Drawing.Color BurlyWood { get { throw null; } }
public static System.Drawing.Color CadetBlue { get { throw null; } }
public static System.Drawing.Color Chartreuse { get { throw null; } }
public static System.Drawing.Color Chocolate { get { throw null; } }
public static System.Drawing.Color Coral { get { throw null; } }
public static System.Drawing.Color CornflowerBlue { get { throw null; } }
public static System.Drawing.Color Cornsilk { get { throw null; } }
public static System.Drawing.Color Crimson { get { throw null; } }
public static System.Drawing.Color Cyan { get { throw null; } }
public static System.Drawing.Color DarkBlue { get { throw null; } }
public static System.Drawing.Color DarkCyan { get { throw null; } }
public static System.Drawing.Color DarkGoldenrod { get { throw null; } }
public static System.Drawing.Color DarkGray { get { throw null; } }
public static System.Drawing.Color DarkGreen { get { throw null; } }
public static System.Drawing.Color DarkKhaki { get { throw null; } }
public static System.Drawing.Color DarkMagenta { get { throw null; } }
public static System.Drawing.Color DarkOliveGreen { get { throw null; } }
public static System.Drawing.Color DarkOrange { get { throw null; } }
public static System.Drawing.Color DarkOrchid { get { throw null; } }
public static System.Drawing.Color DarkRed { get { throw null; } }
public static System.Drawing.Color DarkSalmon { get { throw null; } }
public static System.Drawing.Color DarkSeaGreen { get { throw null; } }
public static System.Drawing.Color DarkSlateBlue { get { throw null; } }
public static System.Drawing.Color DarkSlateGray { get { throw null; } }
public static System.Drawing.Color DarkTurquoise { get { throw null; } }
public static System.Drawing.Color DarkViolet { get { throw null; } }
public static System.Drawing.Color DeepPink { get { throw null; } }
public static System.Drawing.Color DeepSkyBlue { get { throw null; } }
public static System.Drawing.Color DimGray { get { throw null; } }
public static System.Drawing.Color DodgerBlue { get { throw null; } }
public static System.Drawing.Color Firebrick { get { throw null; } }
public static System.Drawing.Color FloralWhite { get { throw null; } }
public static System.Drawing.Color ForestGreen { get { throw null; } }
public static System.Drawing.Color Fuchsia { get { throw null; } }
public byte G { get { throw null; } }
public static System.Drawing.Color Gainsboro { get { throw null; } }
public static System.Drawing.Color GhostWhite { get { throw null; } }
public static System.Drawing.Color Gold { get { throw null; } }
public static System.Drawing.Color Goldenrod { get { throw null; } }
public static System.Drawing.Color Gray { get { throw null; } }
public static System.Drawing.Color Green { get { throw null; } }
public static System.Drawing.Color GreenYellow { get { throw null; } }
public static System.Drawing.Color Honeydew { get { throw null; } }
public static System.Drawing.Color HotPink { get { throw null; } }
public static System.Drawing.Color IndianRed { get { throw null; } }
public static System.Drawing.Color Indigo { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public bool IsKnownColor { get { throw null; } }
public bool IsNamedColor { get { throw null; } }
public bool IsSystemColor { get { throw null; } }
public static System.Drawing.Color Ivory { get { throw null; } }
public static System.Drawing.Color Khaki { get { throw null; } }
public static System.Drawing.Color Lavender { get { throw null; } }
public static System.Drawing.Color LavenderBlush { get { throw null; } }
public static System.Drawing.Color LawnGreen { get { throw null; } }
public static System.Drawing.Color LemonChiffon { get { throw null; } }
public static System.Drawing.Color LightBlue { get { throw null; } }
public static System.Drawing.Color LightCoral { get { throw null; } }
public static System.Drawing.Color LightCyan { get { throw null; } }
public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } }
public static System.Drawing.Color LightGray { get { throw null; } }
public static System.Drawing.Color LightGreen { get { throw null; } }
public static System.Drawing.Color LightPink { get { throw null; } }
public static System.Drawing.Color LightSalmon { get { throw null; } }
public static System.Drawing.Color LightSeaGreen { get { throw null; } }
public static System.Drawing.Color LightSkyBlue { get { throw null; } }
public static System.Drawing.Color LightSlateGray { get { throw null; } }
public static System.Drawing.Color LightSteelBlue { get { throw null; } }
public static System.Drawing.Color LightYellow { get { throw null; } }
public static System.Drawing.Color Lime { get { throw null; } }
public static System.Drawing.Color LimeGreen { get { throw null; } }
public static System.Drawing.Color Linen { get { throw null; } }
public static System.Drawing.Color Magenta { get { throw null; } }
public static System.Drawing.Color Maroon { get { throw null; } }
public static System.Drawing.Color MediumAquamarine { get { throw null; } }
public static System.Drawing.Color MediumBlue { get { throw null; } }
public static System.Drawing.Color MediumOrchid { get { throw null; } }
public static System.Drawing.Color MediumPurple { get { throw null; } }
public static System.Drawing.Color MediumSeaGreen { get { throw null; } }
public static System.Drawing.Color MediumSlateBlue { get { throw null; } }
public static System.Drawing.Color MediumSpringGreen { get { throw null; } }
public static System.Drawing.Color MediumTurquoise { get { throw null; } }
public static System.Drawing.Color MediumVioletRed { get { throw null; } }
public static System.Drawing.Color MidnightBlue { get { throw null; } }
public static System.Drawing.Color MintCream { get { throw null; } }
public static System.Drawing.Color MistyRose { get { throw null; } }
public static System.Drawing.Color Moccasin { get { throw null; } }
public string Name { get { throw null; } }
public static System.Drawing.Color NavajoWhite { get { throw null; } }
public static System.Drawing.Color Navy { get { throw null; } }
public static System.Drawing.Color OldLace { get { throw null; } }
public static System.Drawing.Color Olive { get { throw null; } }
public static System.Drawing.Color OliveDrab { get { throw null; } }
public static System.Drawing.Color Orange { get { throw null; } }
public static System.Drawing.Color OrangeRed { get { throw null; } }
public static System.Drawing.Color Orchid { get { throw null; } }
public static System.Drawing.Color PaleGoldenrod { get { throw null; } }
public static System.Drawing.Color PaleGreen { get { throw null; } }
public static System.Drawing.Color PaleTurquoise { get { throw null; } }
public static System.Drawing.Color PaleVioletRed { get { throw null; } }
public static System.Drawing.Color PapayaWhip { get { throw null; } }
public static System.Drawing.Color PeachPuff { get { throw null; } }
public static System.Drawing.Color Peru { get { throw null; } }
public static System.Drawing.Color Pink { get { throw null; } }
public static System.Drawing.Color Plum { get { throw null; } }
public static System.Drawing.Color PowderBlue { get { throw null; } }
public static System.Drawing.Color Purple { get { throw null; } }
public byte R { get { throw null; } }
public static System.Drawing.Color Red { get { throw null; } }
public static System.Drawing.Color RosyBrown { get { throw null; } }
public static System.Drawing.Color RoyalBlue { get { throw null; } }
public static System.Drawing.Color SaddleBrown { get { throw null; } }
public static System.Drawing.Color Salmon { get { throw null; } }
public static System.Drawing.Color SandyBrown { get { throw null; } }
public static System.Drawing.Color SeaGreen { get { throw null; } }
public static System.Drawing.Color SeaShell { get { throw null; } }
public static System.Drawing.Color Sienna { get { throw null; } }
public static System.Drawing.Color Silver { get { throw null; } }
public static System.Drawing.Color SkyBlue { get { throw null; } }
public static System.Drawing.Color SlateBlue { get { throw null; } }
public static System.Drawing.Color SlateGray { get { throw null; } }
public static System.Drawing.Color Snow { get { throw null; } }
public static System.Drawing.Color SpringGreen { get { throw null; } }
public static System.Drawing.Color SteelBlue { get { throw null; } }
public static System.Drawing.Color Tan { get { throw null; } }
public static System.Drawing.Color Teal { get { throw null; } }
public static System.Drawing.Color Thistle { get { throw null; } }
public static System.Drawing.Color Tomato { get { throw null; } }
public static System.Drawing.Color Transparent { get { throw null; } }
public static System.Drawing.Color Turquoise { get { throw null; } }
public static System.Drawing.Color Violet { get { throw null; } }
public static System.Drawing.Color Wheat { get { throw null; } }
public static System.Drawing.Color White { get { throw null; } }
public static System.Drawing.Color WhiteSmoke { get { throw null; } }
public static System.Drawing.Color Yellow { get { throw null; } }
public static System.Drawing.Color YellowGreen { get { throw null; } }
public bool Equals(System.Drawing.Color other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.Color FromArgb(int argb) { throw null; }
public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; }
public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; }
public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; }
public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; }
public static System.Drawing.Color FromName(string name) { throw null; }
public float GetBrightness() { throw null; }
public override int GetHashCode() { throw null; }
public float GetHue() { throw null; }
public float GetSaturation() { throw null; }
public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; }
public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; }
public int ToArgb() { throw null; }
public System.Drawing.KnownColor ToKnownColor() { throw null; }
public override string ToString() { throw null; }
}
public static partial class ColorTranslator
{
public static System.Drawing.Color FromHtml(string htmlColor) { throw null; }
public static System.Drawing.Color FromOle(int oleColor) { throw null; }
public static System.Drawing.Color FromWin32(int win32Color) { throw null; }
public static string ToHtml(System.Drawing.Color c) { throw null; }
public static int ToOle(System.Drawing.Color c) { throw null; }
public static int ToWin32(System.Drawing.Color c) { throw null; }
}
public enum KnownColor
{
ActiveBorder = 1,
ActiveCaption = 2,
ActiveCaptionText = 3,
AppWorkspace = 4,
Control = 5,
ControlDark = 6,
ControlDarkDark = 7,
ControlLight = 8,
ControlLightLight = 9,
ControlText = 10,
Desktop = 11,
GrayText = 12,
Highlight = 13,
HighlightText = 14,
HotTrack = 15,
InactiveBorder = 16,
InactiveCaption = 17,
InactiveCaptionText = 18,
Info = 19,
InfoText = 20,
Menu = 21,
MenuText = 22,
ScrollBar = 23,
Window = 24,
WindowFrame = 25,
WindowText = 26,
Transparent = 27,
AliceBlue = 28,
AntiqueWhite = 29,
Aqua = 30,
Aquamarine = 31,
Azure = 32,
Beige = 33,
Bisque = 34,
Black = 35,
BlanchedAlmond = 36,
Blue = 37,
BlueViolet = 38,
Brown = 39,
BurlyWood = 40,
CadetBlue = 41,
Chartreuse = 42,
Chocolate = 43,
Coral = 44,
CornflowerBlue = 45,
Cornsilk = 46,
Crimson = 47,
Cyan = 48,
DarkBlue = 49,
DarkCyan = 50,
DarkGoldenrod = 51,
DarkGray = 52,
DarkGreen = 53,
DarkKhaki = 54,
DarkMagenta = 55,
DarkOliveGreen = 56,
DarkOrange = 57,
DarkOrchid = 58,
DarkRed = 59,
DarkSalmon = 60,
DarkSeaGreen = 61,
DarkSlateBlue = 62,
DarkSlateGray = 63,
DarkTurquoise = 64,
DarkViolet = 65,
DeepPink = 66,
DeepSkyBlue = 67,
DimGray = 68,
DodgerBlue = 69,
Firebrick = 70,
FloralWhite = 71,
ForestGreen = 72,
Fuchsia = 73,
Gainsboro = 74,
GhostWhite = 75,
Gold = 76,
Goldenrod = 77,
Gray = 78,
Green = 79,
GreenYellow = 80,
Honeydew = 81,
HotPink = 82,
IndianRed = 83,
Indigo = 84,
Ivory = 85,
Khaki = 86,
Lavender = 87,
LavenderBlush = 88,
LawnGreen = 89,
LemonChiffon = 90,
LightBlue = 91,
LightCoral = 92,
LightCyan = 93,
LightGoldenrodYellow = 94,
LightGray = 95,
LightGreen = 96,
LightPink = 97,
LightSalmon = 98,
LightSeaGreen = 99,
LightSkyBlue = 100,
LightSlateGray = 101,
LightSteelBlue = 102,
LightYellow = 103,
Lime = 104,
LimeGreen = 105,
Linen = 106,
Magenta = 107,
Maroon = 108,
MediumAquamarine = 109,
MediumBlue = 110,
MediumOrchid = 111,
MediumPurple = 112,
MediumSeaGreen = 113,
MediumSlateBlue = 114,
MediumSpringGreen = 115,
MediumTurquoise = 116,
MediumVioletRed = 117,
MidnightBlue = 118,
MintCream = 119,
MistyRose = 120,
Moccasin = 121,
NavajoWhite = 122,
Navy = 123,
OldLace = 124,
Olive = 125,
OliveDrab = 126,
Orange = 127,
OrangeRed = 128,
Orchid = 129,
PaleGoldenrod = 130,
PaleGreen = 131,
PaleTurquoise = 132,
PaleVioletRed = 133,
PapayaWhip = 134,
PeachPuff = 135,
Peru = 136,
Pink = 137,
Plum = 138,
PowderBlue = 139,
Purple = 140,
Red = 141,
RosyBrown = 142,
RoyalBlue = 143,
SaddleBrown = 144,
Salmon = 145,
SandyBrown = 146,
SeaGreen = 147,
SeaShell = 148,
Sienna = 149,
Silver = 150,
SkyBlue = 151,
SlateBlue = 152,
SlateGray = 153,
Snow = 154,
SpringGreen = 155,
SteelBlue = 156,
Tan = 157,
Teal = 158,
Thistle = 159,
Tomato = 160,
Turquoise = 161,
Violet = 162,
Wheat = 163,
White = 164,
WhiteSmoke = 165,
Yellow = 166,
YellowGreen = 167,
ButtonFace = 168,
ButtonHighlight = 169,
ButtonShadow = 170,
GradientActiveCaption = 171,
GradientInactiveCaption = 172,
MenuBar = 173,
MenuHighlight = 174,
}
public partial struct Point : System.IEquatable<System.Drawing.Point>
{
private int _dummyPrimitive;
public static readonly System.Drawing.Point Empty;
public Point(System.Drawing.Size sz) { throw null; }
public Point(int dw) { throw null; }
public Point(int x, int y) { throw null; }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
public int X { get { throw null; } set { } }
public int Y { get { throw null; } set { } }
public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; }
public bool Equals(System.Drawing.Point other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public void Offset(System.Drawing.Point p) { }
public void Offset(int dx, int dy) { }
public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; }
public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; }
public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; }
public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; }
public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; }
public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; }
}
public partial struct PointF : System.IEquatable<System.Drawing.PointF>
{
private int _dummyPrimitive;
public static readonly System.Drawing.PointF Empty;
public PointF(float x, float y) { throw null; }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
public float X { get { throw null; } set { } }
public float Y { get { throw null; } set { } }
public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public bool Equals(System.Drawing.PointF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; }
public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; }
public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public override string ToString() { throw null; }
}
public partial struct Rectangle : System.IEquatable<System.Drawing.Rectangle>
{
private int _dummyPrimitive;
public static readonly System.Drawing.Rectangle Empty;
public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; }
public Rectangle(int x, int y, int width, int height) { throw null; }
[System.ComponentModel.BrowsableAttribute(false)]
public int Bottom { get { throw null; } }
public int Height { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public int Left { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public System.Drawing.Point Location { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public int Right { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public System.Drawing.Size Size { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public int Top { get { throw null; } }
public int Width { get { throw null; } set { } }
public int X { get { throw null; } set { } }
public int Y { get { throw null; } set { } }
public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; }
public bool Contains(System.Drawing.Point pt) { throw null; }
public bool Contains(System.Drawing.Rectangle rect) { throw null; }
public bool Contains(int x, int y) { throw null; }
public bool Equals(System.Drawing.Rectangle other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; }
public void Inflate(System.Drawing.Size size) { }
public void Inflate(int width, int height) { }
public void Intersect(System.Drawing.Rectangle rect) { }
public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
public bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; }
public void Offset(System.Drawing.Point pos) { }
public void Offset(int x, int y) { }
public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; }
public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; }
public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; }
public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
}
public partial struct RectangleF : System.IEquatable<System.Drawing.RectangleF>
{
private int _dummyPrimitive;
public static readonly System.Drawing.RectangleF Empty;
public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; }
public RectangleF(float x, float y, float width, float height) { throw null; }
[System.ComponentModel.BrowsableAttribute(false)]
public float Bottom { get { throw null; } }
public float Height { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public float Left { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public System.Drawing.PointF Location { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public float Right { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
public System.Drawing.SizeF Size { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public float Top { get { throw null; } }
public float Width { get { throw null; } set { } }
public float X { get { throw null; } set { } }
public float Y { get { throw null; } set { } }
public bool Contains(System.Drawing.PointF pt) { throw null; }
public bool Contains(System.Drawing.RectangleF rect) { throw null; }
public bool Contains(float x, float y) { throw null; }
public bool Equals(System.Drawing.RectangleF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; }
public void Inflate(System.Drawing.SizeF size) { }
public void Inflate(float x, float y) { }
public void Intersect(System.Drawing.RectangleF rect) { }
public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; }
public bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; }
public void Offset(System.Drawing.PointF pos) { }
public void Offset(float x, float y) { }
public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; }
public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; }
public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; }
}
public partial struct Size : System.IEquatable<System.Drawing.Size>
{
private int _dummyPrimitive;
public static readonly System.Drawing.Size Empty;
public Size(System.Drawing.Point pt) { throw null; }
public Size(int width, int height) { throw null; }
public int Height { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
public int Width { get { throw null; } set { } }
public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; }
public bool Equals(System.Drawing.Size other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size operator /(System.Drawing.Size left, int right) { throw null; }
public static System.Drawing.SizeF operator /(System.Drawing.Size left, float right) { throw null; }
public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; }
public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; }
public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size operator *(System.Drawing.Size left, int right) { throw null; }
public static System.Drawing.SizeF operator *(System.Drawing.Size left, float right) { throw null; }
public static System.Drawing.Size operator *(int left, System.Drawing.Size right) { throw null; }
public static System.Drawing.SizeF operator *(float left, System.Drawing.Size right) { throw null; }
public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; }
public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; }
}
public partial struct SizeF : System.IEquatable<System.Drawing.SizeF>
{
private int _dummyPrimitive;
public static readonly System.Drawing.SizeF Empty;
public SizeF(System.Drawing.PointF pt) { throw null; }
public SizeF(System.Drawing.SizeF size) { throw null; }
public SizeF(float width, float height) { throw null; }
public float Height { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
public bool IsEmpty { get { throw null; } }
public float Width { get { throw null; } set { } }
public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public bool Equals(System.Drawing.SizeF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static System.Drawing.SizeF operator /(System.Drawing.SizeF left, float right) { throw null; }
public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; }
public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static System.Drawing.SizeF operator *(System.Drawing.SizeF left, float right) { throw null; }
public static System.Drawing.SizeF operator *(float left, System.Drawing.SizeF right) { throw null; }
public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public System.Drawing.PointF ToPointF() { throw null; }
public System.Drawing.Size ToSize() { throw null; }
public override string ToString() { throw null; }
}
public static partial class SystemColors
{
public static System.Drawing.Color ActiveBorder { get { throw null; } }
public static System.Drawing.Color ActiveCaption { get { throw null; } }
public static System.Drawing.Color ActiveCaptionText { get { throw null; } }
public static System.Drawing.Color AppWorkspace { get { throw null; } }
public static System.Drawing.Color ButtonFace { get { throw null; } }
public static System.Drawing.Color ButtonHighlight { get { throw null; } }
public static System.Drawing.Color ButtonShadow { get { throw null; } }
public static System.Drawing.Color Control { get { throw null; } }
public static System.Drawing.Color ControlDark { get { throw null; } }
public static System.Drawing.Color ControlDarkDark { get { throw null; } }
public static System.Drawing.Color ControlLight { get { throw null; } }
public static System.Drawing.Color ControlLightLight { get { throw null; } }
public static System.Drawing.Color ControlText { get { throw null; } }
public static System.Drawing.Color Desktop { get { throw null; } }
public static System.Drawing.Color GradientActiveCaption { get { throw null; } }
public static System.Drawing.Color GradientInactiveCaption { get { throw null; } }
public static System.Drawing.Color GrayText { get { throw null; } }
public static System.Drawing.Color Highlight { get { throw null; } }
public static System.Drawing.Color HighlightText { get { throw null; } }
public static System.Drawing.Color HotTrack { get { throw null; } }
public static System.Drawing.Color InactiveBorder { get { throw null; } }
public static System.Drawing.Color InactiveCaption { get { throw null; } }
public static System.Drawing.Color InactiveCaptionText { get { throw null; } }
public static System.Drawing.Color Info { get { throw null; } }
public static System.Drawing.Color InfoText { get { throw null; } }
public static System.Drawing.Color Menu { get { throw null; } }
public static System.Drawing.Color MenuBar { get { throw null; } }
public static System.Drawing.Color MenuHighlight { get { throw null; } }
public static System.Drawing.Color MenuText { get { throw null; } }
public static System.Drawing.Color ScrollBar { get { throw null; } }
public static System.Drawing.Color Window { get { throw null; } }
public static System.Drawing.Color WindowFrame { get { throw null; } }
public static System.Drawing.Color WindowText { get { throw null; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace John.Doyle.Mediocore.Developer.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Azure.Data.Tables.Queryable
{
internal class ExpressionWriter : LinqExpressionVisitor
{
internal readonly StringBuilder _builder;
private readonly Stack<Expression> _expressionStack;
private bool _cantTranslateExpression;
protected ExpressionWriter()
{
_builder = new StringBuilder();
_expressionStack = new Stack<Expression>();
_expressionStack.Push(null);
}
internal static string ExpressionToString(Expression e)
{
ExpressionWriter ew = new ExpressionWriter();
return ew.ConvertExpressionToString(e);
}
internal string ConvertExpressionToString(Expression e)
{
string serialized = Translate(e);
if (_cantTranslateExpression)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantTranslateExpression, e.ToString()));
}
return serialized;
}
internal override Expression Visit(Expression exp)
{
_expressionStack.Push(exp);
Expression result = base.Visit(exp);
_expressionStack.Pop();
return result;
}
internal override Expression VisitMethodCall(MethodCallExpression m)
{
if (ReflectionUtil.s_dictionaryMethodInfosHash.Contains(m.Method) && m.Arguments.Count == 1 && m.Arguments[0] is ConstantExpression ce)
{
_builder.Append(ce.Value as string);
}
else
{
return base.VisitMethodCall(m);
}
return m;
}
internal override Expression VisitMemberAccess(MemberExpression m)
{
if (m.Member is FieldInfo)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantReferToPublicField, m.Member.Name));
}
Expression e = Visit(m.Expression);
if (m.Member.Name == "Value" && m.Member.DeclaringType.IsGenericType
&& m.Member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return m;
}
if (!IsInputReference(e) && e.NodeType != ExpressionType.Convert && e.NodeType != ExpressionType.ConvertChecked)
{
_builder.Append(UriHelper.FORWARDSLASH);
}
_builder.Append(TranslateMemberName(m.Member.Name));
return m;
}
internal override Expression VisitConstant(ConstantExpression c)
{
string result;
if (c.Value == null)
{
_builder.Append(UriHelper.NULL);
return c;
}
else if (!ClientConvert.TryKeyPrimitiveToString(c.Value, out result))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCouldNotConvert, c.Value));
}
Debug.Assert(result != null, "result != null");
// A Difference from WCF Data Services is that we will escape later when we execute the fully parsed query.
_builder.Append(result);
return c;
}
internal override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
_builder.Append(UriHelper.NOT);
_builder.Append(UriHelper.SPACE);
VisitOperand(u.Operand);
break;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
_builder.Append(UriHelper.SPACE);
_builder.Append(TranslateOperator(u.NodeType));
VisitOperand(u.Operand);
break;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.UnaryPlus:
break;
default:
_cantTranslateExpression = true;
break;
}
return u;
}
internal override Expression VisitBinary(BinaryExpression b)
{
VisitOperand(b.Left);
_builder.Append(UriHelper.SPACE);
string operatorString = TranslateOperator(b.NodeType);
if (string.IsNullOrEmpty(operatorString))
{
_cantTranslateExpression = true;
}
else
{
_builder.Append(operatorString);
}
_builder.Append(UriHelper.SPACE);
VisitOperand(b.Right);
return b;
}
internal override Expression VisitParameter(ParameterExpression p)
{
return p;
}
private static bool IsInputReference(Expression exp)
{
return exp is ParameterExpression;
}
private void VisitOperand(Expression e)
{
if (e is BinaryExpression || e is UnaryExpression)
{
if (e is UnaryExpression unary && unary.NodeType == ExpressionType.TypeAs)
{
Visit(unary.Operand);
}
else
{
_builder.Append(UriHelper.LEFTPAREN);
Visit(e);
_builder.Append(UriHelper.RIGHTPAREN);
}
}
else
{
Visit(e);
}
}
private string Translate(Expression e)
{
Visit(e);
return _builder.ToString();
}
protected virtual string TranslateMemberName(string memberName)
{
return memberName;
}
protected virtual string TranslateOperator(ExpressionType type)
{
switch (type)
{
case ExpressionType.AndAlso:
case ExpressionType.And:
return UriHelper.AND;
case ExpressionType.OrElse:
case ExpressionType.Or:
return UriHelper.OR;
case ExpressionType.Equal:
return UriHelper.EQ;
case ExpressionType.NotEqual:
return UriHelper.NE;
case ExpressionType.LessThan:
return UriHelper.LT;
case ExpressionType.LessThanOrEqual:
return UriHelper.LE;
case ExpressionType.GreaterThan:
return UriHelper.GT;
case ExpressionType.GreaterThanOrEqual:
return UriHelper.GE;
case ExpressionType.Add:
case ExpressionType.AddChecked:
return UriHelper.ADD;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return UriHelper.SUB;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return UriHelper.MUL;
case ExpressionType.Divide:
return UriHelper.DIV;
case ExpressionType.Modulo:
return UriHelper.MOD;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
return UriHelper.NEGATE;
case ExpressionType.ArrayIndex:
case ExpressionType.Power:
case ExpressionType.Coalesce:
case ExpressionType.ExclusiveOr:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
default:
return null;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CSharpSocket.cs" company="Exit Games GmbH">
// Protocol & Photon Client Lib - Copyright (C) 2013 Exit Games GmbH
// </copyright>
// <summary>
// Uses the UDP socket for a peer to send and receive enet/Photon messages.
// </summary>
// <author>[email protected]</author>
// --------------------------------------------------------------------------------------------------------------------
#if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE && !UNITY_PS3 && !UNITY_WINRT && !UNITY_WP8)
namespace ExitGames.Client.Photon
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.Threading;
/// <summary> Internal class to encapsulate the network i/o functionality for the realtime libary.</summary>
internal class SocketUdp : IPhotonSocket, IDisposable
{
private Socket sock;
private readonly object syncer = new object();
public SocketUdp(PeerBase npeer) : base(npeer)
{
if (this.ReportDebugOfLevel(DebugLevel.ALL))
{
this.Listener.DebugReturn(DebugLevel.ALL, "CSharpSocket: UDP, Unity3d.");
}
this.Protocol = ConnectionProtocol.Udp;
this.PollReceive = false;
}
public void Dispose()
{
this.State = PhotonSocketState.Disconnecting;
if (this.sock != null)
{
try
{
if (this.sock.Connected) this.sock.Close();
}
catch (Exception ex)
{
this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in Dispose(): " + ex);
}
}
this.sock = null;
this.State = PhotonSocketState.Disconnected;
}
public override bool Connect()
{
lock (this.syncer)
{
bool baseOk = base.Connect();
if (!baseOk)
{
return false;
}
this.State = PhotonSocketState.Connecting;
Thread dns = new Thread(this.DnsAndConnect);
dns.Name = "photon dns thread";
dns.IsBackground = true;
dns.Start();
return true;
}
}
public override bool Disconnect()
{
if (this.ReportDebugOfLevel(DebugLevel.INFO))
{
this.EnqueueDebugReturn(DebugLevel.INFO, "CSharpSocket.Disconnect()");
}
this.State = PhotonSocketState.Disconnecting;
lock (this.syncer)
{
if (this.sock != null)
{
try
{
this.sock.Close();
}
catch (Exception ex)
{
this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in Disconnect(): " + ex);
}
this.sock = null;
}
}
this.State = PhotonSocketState.Disconnected;
return true;
}
/// <summary>used by PhotonPeer*</summary>
public override PhotonSocketError Send(byte[] data, int length)
{
lock (this.syncer)
{
if (this.sock == null || !this.sock.Connected)
{
return PhotonSocketError.Skipped;
}
try
{
sock.Send(data, 0, length, SocketFlags.None);
}
catch (Exception e)
{
if (this.ReportDebugOfLevel(DebugLevel.ERROR))
{
this.EnqueueDebugReturn(DebugLevel.ERROR, "Cannot send to: " + this.ServerAddress + ". " + e.Message);
}
return PhotonSocketError.Exception;
}
}
return PhotonSocketError.Success;
}
public override PhotonSocketError Receive(out byte[] data)
{
data = null;
return PhotonSocketError.NoData;
}
internal void DnsAndConnect()
{
IPAddress ipAddress = null;
try
{
lock (this.syncer)
{
ipAddress = IPhotonSocket.GetIpAddress(this.ServerAddress);
if (ipAddress == null)
{
throw new ArgumentException("Invalid IPAddress. Address: " + this.ServerAddress);
}
if (ipAddress.AddressFamily != AddressFamily.InterNetwork && ipAddress.AddressFamily != AddressFamily.InterNetworkV6)
{
throw new ArgumentException("AddressFamily '" + ipAddress.AddressFamily + "' not supported. Address: " + this.ServerAddress);
}
this.sock = new Socket(ipAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
this.sock.Connect(ipAddress, this.ServerPort);
this.State = PhotonSocketState.Connected;
this.peerBase.SetInitIPV6Bit(ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6);
this.peerBase.OnConnect();
}
}
catch (SecurityException se)
{
if (this.ReportDebugOfLevel(DebugLevel.ERROR))
{
this.Listener.DebugReturn(DebugLevel.ERROR, "Connect() to '" + this.ServerAddress + "' (" + ((ipAddress == null ) ? "": ipAddress.AddressFamily.ToString()) + ") failed: " + se.ToString());
}
this.HandleException(StatusCode.SecurityExceptionOnConnect);
return;
}
catch (Exception se)
{
if (this.ReportDebugOfLevel(DebugLevel.ERROR))
{
this.Listener.DebugReturn(DebugLevel.ERROR, "Connect() to '" + this.ServerAddress + "' (" + ((ipAddress == null) ? "" : ipAddress.AddressFamily.ToString()) + ") failed: " + se.ToString());
}
this.HandleException(StatusCode.ExceptionOnConnect);
return;
}
Thread run = new Thread(new ThreadStart(ReceiveLoop));
run.Name = "photon receive thread";
run.IsBackground = true;
run.Start();
}
/// <summary>Endless loop, run in Receive Thread.</summary>
public void ReceiveLoop()
{
byte[] inBuffer = new byte[this.MTU];
while (this.State == PhotonSocketState.Connected)
{
try
{
int read = this.sock.Receive(inBuffer);
this.HandleReceivedDatagram(inBuffer, read, true);
}
catch (Exception e)
{
if (this.State != PhotonSocketState.Disconnecting && this.State != PhotonSocketState.Disconnected)
{
if (this.ReportDebugOfLevel(DebugLevel.ERROR))
{
this.EnqueueDebugReturn(DebugLevel.ERROR, "Receive issue. State: " + this.State + ". Server: '" + this.ServerAddress + "' Exception: " + e);
}
this.HandleException(StatusCode.ExceptionOnReceive);
}
}
} //while Connected receive
// on exit of the receive-loop: disconnect socket
this.Disconnect();
}
} //class
}
#endif
| |
using System;
using System.Collections.Generic;
using Content.Server.Power.Components;
using Content.Server.UserInterface;
using Content.Server.VendingMachines;
using Content.Server.WireHacking;
using Content.Shared.ActionBlocker;
using Content.Shared.Arcade;
using Content.Shared.Interaction;
using Content.Shared.Sound;
using Content.Shared.Wires;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;
using Robust.Shared.ViewVariables;
namespace Content.Server.Arcade.Components
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
public sealed class SpaceVillainArcadeComponent : SharedSpaceVillainArcadeComponent, IActivate, IWires
{
[Dependency] private readonly IRobustRandom _random = null!;
[Dependency] private readonly IEntityManager _entityManager = default!;
private bool Powered => _entityManager.TryGetComponent<ApcPowerReceiverComponent>(Owner, out var powerReceiverComponent) && powerReceiverComponent.Powered;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SpaceVillainArcadeUiKey.Key);
[ViewVariables] private bool _overflowFlag;
[ViewVariables] private bool _playerInvincibilityFlag;
[ViewVariables] private bool _enemyInvincibilityFlag;
[ViewVariables] private SpaceVillainGame _game = null!;
[DataField("newGameSound")] private SoundSpecifier _newGameSound = new SoundPathSpecifier("/Audio/Effects/Arcade/newgame.ogg");
[DataField("playerAttackSound")] private SoundSpecifier _playerAttackSound = new SoundPathSpecifier("/Audio/Effects/Arcade/player_attack.ogg");
[DataField("playerHealSound")] private SoundSpecifier _playerHealSound = new SoundPathSpecifier("/Audio/Effects/Arcade/player_heal.ogg");
[DataField("playerChargeSound")] private SoundSpecifier _playerChargeSound = new SoundPathSpecifier("/Audio/Effects/Arcade/player_charge.ogg");
[DataField("winSound")] private SoundSpecifier _winSound = new SoundPathSpecifier("/Audio/Effects/Arcade/win.ogg");
[DataField("gameOverSound")] private SoundSpecifier _gameOverSound = new SoundPathSpecifier("/Audio/Effects/Arcade/gameover.ogg");
[ViewVariables(VVAccess.ReadWrite)]
[DataField("possibleFightVerbs")]
private List<string> _possibleFightVerbs = new List<string>()
{"Defeat", "Annihilate", "Save", "Strike", "Stop", "Destroy", "Robust", "Romance", "Pwn", "Own"};
[ViewVariables(VVAccess.ReadWrite)]
[DataField("possibleFirstEnemyNames")]
private List<string> _possibleFirstEnemyNames = new List<string>(){
"the Automatic", "Farmer", "Lord", "Professor", "the Cuban", "the Evil", "the Dread King",
"the Space", "Lord", "the Great", "Duke", "General"
};
[ViewVariables(VVAccess.ReadWrite)]
[DataField("possibleLastEnemyNames")]
private List<string> _possibleLastEnemyNames = new List<string>()
{
"Melonoid", "Murdertron", "Sorcerer", "Ruin", "Jeff", "Ectoplasm", "Crushulon", "Uhangoid",
"Vhakoid", "Peteoid", "slime", "Griefer", "ERPer", "Lizard Man", "Unicorn"
};
[ViewVariables(VVAccess.ReadWrite)]
[DataField("possibleRewards", customTypeSerializer:typeof(PrototypeIdListSerializer<EntityPrototype>))]
private List<string> _possibleRewards = new List<string>()
{
"ToyMouse", "ToyAi", "ToyNuke", "ToyAssistant", "ToyGriffin", "ToyHonk", "ToyIan",
"ToyMarauder", "ToyMauler", "ToyGygax", "ToyOdysseus", "ToyOwlman", "ToyDeathRipley",
"ToyPhazon", "ToyFireRipley", "ToyReticence", "ToyRipley", "ToySeraph", "ToyDurand", "ToySkeleton"
};
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!Powered || !IoCManager.Resolve<IEntityManager>().TryGetComponent(eventArgs.User, out ActorComponent? actor))
return;
_game ??= new SpaceVillainGame(this);
if (_entityManager.TryGetComponent<WiresComponent>(Owner, out var wiresComponent) && wiresComponent.IsPanelOpen)
{
wiresComponent.OpenInterface(actor.PlayerSession);
}
else
{
UserInterface?.Toggle(actor.PlayerSession);
}
}
protected override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage;
}
}
[Obsolete("Component Messages are deprecated, use Entity Events instead.")]
public override void HandleMessage(ComponentMessage message, IComponent? component)
{
#pragma warning disable 618
base.HandleMessage(message, component);
#pragma warning restore 618
switch (message)
{
case PowerChangedMessage powerChanged:
OnOnPowerStateChanged(powerChanged);
break;
}
}
private void OnOnPowerStateChanged(PowerChangedMessage e)
{
if (e.Powered) return;
UserInterface?.CloseAll();
}
private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg)
{
if (!Powered)
return;
if (serverMsg.Message is not SpaceVillainArcadePlayerActionMessage msg) return;
switch (msg.PlayerAction)
{
case PlayerAction.Attack:
_game?.ExecutePlayerAction(msg.PlayerAction);
break;
case PlayerAction.Heal:
_game?.ExecutePlayerAction(msg.PlayerAction);
break;
case PlayerAction.Recharge:
_game?.ExecutePlayerAction(msg.PlayerAction);
break;
case PlayerAction.NewGame:
SoundSystem.Play(Filter.Pvs(Owner), _newGameSound.GetSound(), Owner, AudioParams.Default.WithVolume(-4f));
_game = new SpaceVillainGame(this);
UserInterface?.SendMessage(_game.GenerateMetaDataMessage());
break;
case PlayerAction.RequestData:
UserInterface?.SendMessage(_game.GenerateMetaDataMessage());
break;
}
}
public enum Wires
{
/// <summary>
/// Disables Max Health&Mana for both Enemy and Player.
/// </summary>
Overflow,
/// <summary>
/// Makes Player Invincible.
/// </summary>
PlayerInvincible,
/// <summary>
/// Makes Enemy Invincible.
/// </summary>
EnemyInvincible
}
public void RegisterWires(WiresComponent.WiresBuilder builder)
{
builder.CreateWire(Wires.Overflow);
builder.CreateWire(Wires.PlayerInvincible);
builder.CreateWire(Wires.EnemyInvincible);
builder.CreateWire(4);
builder.CreateWire(5);
builder.CreateWire(6);
IndicatorUpdate();
}
public void WiresUpdate(WiresUpdateEventArgs args)
{
var wire = (Wires) args.Identifier;
var value = args.Action != SharedWiresComponent.WiresAction.Mend;
switch (wire)
{
case Wires.Overflow:
_overflowFlag = value;
break;
case Wires.PlayerInvincible:
_playerInvincibilityFlag = value;
break;
case Wires.EnemyInvincible:
_enemyInvincibilityFlag = value;
break;
}
IndicatorUpdate();
}
public void IndicatorUpdate()
{
if (!_entityManager.TryGetComponent<WiresComponent>(Owner, out var wiresComponent)) return;
wiresComponent.SetStatus(Indicators.HealthManager,
new SharedWiresComponent.StatusLightData(Color.Purple,
_playerInvincibilityFlag || _enemyInvincibilityFlag
? SharedWiresComponent.StatusLightState.BlinkingSlow
: SharedWiresComponent.StatusLightState.On,
"MNGR"));
wiresComponent.SetStatus(Indicators.HealthLimiter,
new SharedWiresComponent.StatusLightData(Color.Red,
_overflowFlag
? SharedWiresComponent.StatusLightState.BlinkingSlow
: SharedWiresComponent.StatusLightState.On,
"LIMT"));
}
/// <summary>
/// Called when the user wins the game.
/// </summary>
public void ProcessWin()
{
var entityManager = IoCManager.Resolve<IEntityManager>();
entityManager.SpawnEntity(_random.Pick(_possibleRewards), entityManager.GetComponent<TransformComponent>(Owner).MapPosition);
}
/// <summary>
/// Picks a fight-verb from the list of possible Verbs.
/// </summary>
/// <returns>A fight-verb.</returns>
public string GenerateFightVerb()
{
return _random.Pick(_possibleFightVerbs);
}
/// <summary>
/// Generates an enemy-name comprised of a first- and last-name.
/// </summary>
/// <returns>An enemy-name.</returns>
public string GenerateEnemyName()
{
return $"{_random.Pick(_possibleFirstEnemyNames)} {_random.Pick(_possibleLastEnemyNames)}";
}
/// <summary>
/// A Class to handle all the game-logic of the SpaceVillain-game.
/// </summary>
public sealed class SpaceVillainGame
{
[Dependency] private readonly IRobustRandom _random = default!;
[ViewVariables] private readonly SpaceVillainArcadeComponent _owner;
[ViewVariables] public string Name => $"{_fightVerb} {_enemyName}";
[ViewVariables(VVAccess.ReadWrite)] private int _playerHp = 30;
[ViewVariables(VVAccess.ReadWrite)] private int _playerHpMax = 30;
[ViewVariables(VVAccess.ReadWrite)] private int _playerMp = 10;
[ViewVariables(VVAccess.ReadWrite)] private int _playerMpMax = 10;
[ViewVariables(VVAccess.ReadWrite)] private int _enemyHp = 45;
[ViewVariables(VVAccess.ReadWrite)] private int _enemyHpMax = 45;
[ViewVariables(VVAccess.ReadWrite)] private int _enemyMp = 20;
[ViewVariables(VVAccess.ReadWrite)] private int _enemyMpMax = 20;
[ViewVariables(VVAccess.ReadWrite)] private int _turtleTracker;
[ViewVariables(VVAccess.ReadWrite)] private readonly string _fightVerb;
[ViewVariables(VVAccess.ReadWrite)] private readonly string _enemyName;
[ViewVariables] private bool _running = true;
private string _latestPlayerActionMessage = "";
private string _latestEnemyActionMessage = "";
public SpaceVillainGame(SpaceVillainArcadeComponent owner) : this(owner, owner.GenerateFightVerb(), owner.GenerateEnemyName()) { }
public SpaceVillainGame(SpaceVillainArcadeComponent owner, string fightVerb, string enemyName)
{
IoCManager.InjectDependencies(this);
_owner = owner;
//todo defeat the curse secret game mode
_fightVerb = fightVerb;
_enemyName = enemyName;
}
/// <summary>
/// Validates all vars incase they overshoot their max-values.
/// Does not check if vars surpass 0.
/// </summary>
private void ValidateVars()
{
if (_owner._overflowFlag) return;
if (_playerHp > _playerHpMax) _playerHp = _playerHpMax;
if (_playerMp > _playerMpMax) _playerMp = _playerMpMax;
if (_enemyHp > _enemyHpMax) _enemyHp = _enemyHpMax;
if (_enemyMp > _enemyMpMax) _enemyMp = _enemyMpMax;
}
/// <summary>
/// Called by the SpaceVillainArcadeComponent when Userinput is received.
/// </summary>
/// <param name="action">The action the user picked.</param>
public void ExecutePlayerAction(PlayerAction action)
{
if (!_running) return;
switch (action)
{
case PlayerAction.Attack:
var attackAmount = _random.Next(2, 6);
_latestPlayerActionMessage = Loc.GetString("space-villain-game-player-attack-message",
("enemyName", _enemyName),
("attackAmount", attackAmount));
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._playerAttackSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
if (!_owner._enemyInvincibilityFlag)
_enemyHp -= attackAmount;
_turtleTracker -= _turtleTracker > 0 ? 1 : 0;
break;
case PlayerAction.Heal:
var pointAmount = _random.Next(1, 3);
var healAmount = _random.Next(6, 8);
_latestPlayerActionMessage = Loc.GetString("space-villain-game-player-heal-message",
("magicPointAmount", pointAmount),
("healAmount", healAmount));
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._playerHealSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
if (!_owner._playerInvincibilityFlag)
_playerMp -= pointAmount;
_playerHp += healAmount;
_turtleTracker++;
break;
case PlayerAction.Recharge:
var chargeAmount = _random.Next(4, 7);
_latestPlayerActionMessage = Loc.GetString("space-villain-game-player-recharge-message", ("regainedPoints", chargeAmount));
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._playerChargeSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
_playerMp += chargeAmount;
_turtleTracker -= _turtleTracker > 0 ? 1 : 0;
break;
}
if (!CheckGameConditions())
{
return;
}
ValidateVars();
ExecuteAiAction();
if (!CheckGameConditions())
{
return;
}
ValidateVars();
UpdateUi();
}
/// <summary>
/// Checks the Game conditions and Updates the Ui & Plays a sound accordingly.
/// </summary>
/// <returns>A bool indicating if the game should continue.</returns>
private bool CheckGameConditions()
{
if ((_playerHp > 0 && _playerMp > 0) && (_enemyHp <= 0 || _enemyMp <= 0))
{
_running = false;
UpdateUi(Loc.GetString("space-villain-game-player-wins-message"),
Loc.GetString("space-villain-game-enemy-dies-message", ("enemyName", _enemyName)),
true);
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._winSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
_owner.ProcessWin();
return false;
}
if (_playerHp > 0 && _playerMp > 0) return true;
if ((_enemyHp > 0 && _enemyMp > 0))
{
_running = false;
UpdateUi(Loc.GetString("space-villain-game-player-loses-message"),
Loc.GetString("space-villain-game-enemy-cheers-message", ("enemyName", _enemyName)),
true);
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._gameOverSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
return false;
}
if (_enemyHp <= 0 || _enemyMp <= 0)
{
_running = false;
UpdateUi(Loc.GetString("space-villain-game-player-loses-message"),
Loc.GetString("space-villain-game-enemy-dies-with-player-message ", ("enemyName", _enemyName)),
true);
SoundSystem.Play(Filter.Pvs(_owner.Owner), _owner._gameOverSound.GetSound(), _owner.Owner, AudioParams.Default.WithVolume(-4f));
return false;
}
return true;
}
/// <summary>
/// Updates the UI.
/// </summary>
private void UpdateUi(bool metadata = false)
{
_owner.UserInterface?.SendMessage(metadata ? GenerateMetaDataMessage() : GenerateUpdateMessage());
}
private void UpdateUi(string message1, string message2, bool metadata = false)
{
_latestPlayerActionMessage = message1;
_latestEnemyActionMessage = message2;
UpdateUi(metadata);
}
/// <summary>
/// Handles the logic of the AI
/// </summary>
/// <returns>An Enemyaction-message.</returns>
private void ExecuteAiAction()
{
if (_turtleTracker >= 4)
{
var boomAmount = _random.Next(5, 10);
_latestEnemyActionMessage = Loc.GetString("space-villain-game-enemy-throws-bomb-message",
("enemyName", _enemyName),
("damageReceived", boomAmount));
if (_owner._playerInvincibilityFlag) return;
_playerHp -= boomAmount;
_turtleTracker--;
}
else if (_enemyMp <= 5 && _random.Prob(0.7f))
{
var stealAmount = _random.Next(2, 3);
_latestEnemyActionMessage = Loc.GetString("space-villain-game-enemy-steals-player-power-message",
("enemyName", _enemyName),
("stolenAmount", stealAmount));
if (_owner._playerInvincibilityFlag) return;
_playerMp -= stealAmount;
_enemyMp += stealAmount;
}
else if (_enemyHp <= 10 && _enemyMp > 4)
{
_enemyHp += 4;
_enemyMp -= 4;
_latestEnemyActionMessage = Loc.GetString("space-villain-game-enemy-heals-message",
("enemyName", _enemyName),
("healedAmount", 4));
}
else
{
var attackAmount = _random.Next(3, 6);
_latestEnemyActionMessage =
Loc.GetString("space-villain-game-enemy-attacks-message",
("enemyName", _enemyName),
("damageDealt", attackAmount));
if (_owner._playerInvincibilityFlag) return;
_playerHp -= attackAmount;
}
}
/// <summary>
/// Generates a Metadata-message based on the objects values.
/// </summary>
/// <returns>A Metadata-message.</returns>
public SpaceVillainArcadeMetaDataUpdateMessage GenerateMetaDataMessage()
{
return new(_playerHp, _playerMp, _enemyHp, _enemyMp, _latestPlayerActionMessage, _latestEnemyActionMessage, Name, _enemyName, !_running);
}
/// <summary>
/// Creates an Update-message based on the objects values.
/// </summary>
/// <returns>An Update-Message.</returns>
public SpaceVillainArcadeDataUpdateMessage
GenerateUpdateMessage()
{
return new(_playerHp, _playerMp, _enemyHp, _enemyMp, _latestPlayerActionMessage,
_latestEnemyActionMessage);
}
}
}
}
| |
// 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;
namespace System.Security.Cryptography
{
public class CryptoConfig
{
private const string AssemblyName_Cng = "System.Security.Cryptography.Cng";
private const string AssemblyName_Csp = "System.Security.Cryptography.Csp";
private const string AssemblyName_Pkcs = "System.Security.Cryptography.Pkcs";
private const string AssemblyName_X509Certificates = "System.Security.Cryptography.X509Certificates";
private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
private const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6";
private const string OID_RSA_MD5 = "1.2.840.113549.2.5";
private const string OID_RSA_RC2CBC = "1.2.840.113549.3.2";
private const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7";
private const string OID_OIWSEC_desCBC = "1.3.14.3.2.7";
private const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26";
private const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1";
private const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2";
private const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3";
private const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1";
private static volatile Dictionary<string, string> s_defaultOidHT = null;
private static volatile Dictionary<string, object> s_defaultNameHT = null;
private static readonly char[] SepArray = { '.' }; // valid ASN.1 separators
// CoreFx does not support AllowOnlyFipsAlgorithms
public static bool AllowOnlyFipsAlgorithms => false;
private static Dictionary<string, string> DefaultOidHT
{
get
{
if (s_defaultOidHT != null)
{
return s_defaultOidHT;
}
Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
ht.Add("SHA", OID_OIWSEC_SHA1);
ht.Add("SHA1", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1Cng", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1Managed", OID_OIWSEC_SHA1);
ht.Add("SHA256", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256Cng", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256Managed", OID_OIWSEC_SHA256);
ht.Add("SHA384", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Cng", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Managed", OID_OIWSEC_SHA384);
ht.Add("SHA512", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Cng", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Managed", OID_OIWSEC_SHA512);
ht.Add("RIPEMD160", OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160", OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160Managed", OID_OIWSEC_RIPEMD160);
ht.Add("MD5", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5Managed", OID_RSA_MD5);
ht.Add("TripleDESKeyWrap", OID_RSA_SMIMEalgCMS3DESwrap);
ht.Add("RC2", OID_RSA_RC2CBC);
ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", OID_RSA_RC2CBC);
ht.Add("DES", OID_OIWSEC_desCBC);
ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", OID_OIWSEC_desCBC);
ht.Add("TripleDES", OID_RSA_DES_EDE3_CBC);
ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", OID_RSA_DES_EDE3_CBC);
s_defaultOidHT = ht;
return s_defaultOidHT;
}
}
private static Dictionary<string, object> DefaultNameHT
{
get
{
if (s_defaultNameHT != null)
{
return s_defaultNameHT;
}
Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5);
Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1);
Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256);
Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384);
Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512);
Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged);
Type AesManagedType = typeof(System.Security.Cryptography.AesManaged);
Type SHA256DefaultType = typeof(System.Security.Cryptography.SHA256Managed);
Type SHA384DefaultType = typeof(System.Security.Cryptography.SHA384Managed);
Type SHA512DefaultType = typeof(System.Security.Cryptography.SHA512Managed);
string SHA1CryptoServiceProviderType = "System.Security.Cryptography.SHA1CryptoServiceProvider, " + AssemblyName_Csp;
string MD5CryptoServiceProviderType = "System.Security.Cryptography.MD5CryptoServiceProvider," + AssemblyName_Csp;
string RSACryptoServiceProviderType = "System.Security.Cryptography.RSACryptoServiceProvider, " + AssemblyName_Csp;
string DSACryptoServiceProviderType = "System.Security.Cryptography.DSACryptoServiceProvider, " + AssemblyName_Csp;
string DESCryptoServiceProviderType = "System.Security.Cryptography.DESCryptoServiceProvider, " + AssemblyName_Csp;
string TripleDESCryptoServiceProviderType = "System.Security.Cryptography.TripleDESCryptoServiceProvider, " + AssemblyName_Csp;
string RC2CryptoServiceProviderType = "System.Security.Cryptography.RC2CryptoServiceProvider, " + AssemblyName_Csp;
string RNGCryptoServiceProviderType = "System.Security.Cryptography.RNGCryptoServiceProvider, " + AssemblyName_Csp;
string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyName_Csp;
string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyName_Cng;
// Random number generator
ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType);
// Hash functions
ht.Add("SHA", SHA1CryptoServiceProviderType);
ht.Add("SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType);
ht.Add("MD5", MD5CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType);
ht.Add("SHA256", SHA256DefaultType);
ht.Add("SHA-256", SHA256DefaultType);
ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType);
ht.Add("SHA384", SHA384DefaultType);
ht.Add("SHA-384", SHA384DefaultType);
ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType);
ht.Add("SHA512", SHA512DefaultType);
ht.Add("SHA-512", SHA512DefaultType);
ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType);
// Keyed Hash Algorithms
ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type);
ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type);
ht.Add("HMACMD5", HMACMD5Type);
ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type);
ht.Add("HMACSHA1", HMACSHA1Type);
ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type);
ht.Add("HMACSHA256", HMACSHA256Type);
ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type);
ht.Add("HMACSHA384", HMACSHA384Type);
ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type);
ht.Add("HMACSHA512", HMACSHA512Type);
ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type);
// Asymmetric algorithms
ht.Add("RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType);
ht.Add("DSA", DSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType);
ht.Add("ECDsa", ECDsaCngType);
ht.Add("ECDsaCng", ECDsaCngType);
ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType);
// Symmetric algorithms
ht.Add("DES", DESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType);
ht.Add("3DES", TripleDESCryptoServiceProviderType);
ht.Add("TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("Triple DES", TripleDESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("RC2", RC2CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType);
ht.Add("Rijndael", RijndaelManagedType);
ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType);
// Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere
ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType);
ht.Add("AES", AesCryptoServiceProviderType);
ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType);
ht.Add("AesManaged", AesManagedType);
ht.Add("System.Security.Cryptography.AesManaged", AesManagedType);
// Xml Dsig/ Enc Hash algorithms
ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType);
// Add the other hash algorithms introduced with XML Encryption
ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType);
ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType);
// Xml Encryption symmetric keys
ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType);
// Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/
ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type);
// Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt
ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type);
// X509 Extensions (custom decoders)
// Basic Constraints OID value
ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates);
ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates);
// Subject Key Identifier OID value
ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyName_X509Certificates);
// Key Usage OID value
ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyName_X509Certificates);
// Enhanced Key Usage OID value
ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyName_X509Certificates);
// X509Chain class can be overridden to use a different chain engine.
ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyName_X509Certificates);
// PKCS9 attributes
ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyName_Pkcs);
ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyName_Pkcs);
ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyName_Pkcs);
ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyName_Pkcs);
ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyName_Pkcs);
s_defaultNameHT = ht;
return s_defaultNameHT;
// Types in Desktop but currently unsupported in CoreFx:
// Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160);
// Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES);
// Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription);
// Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription);
// Type RSAPKCS1SHA256SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA256SignatureDescription);
// Type RSAPKCS1SHA384SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA384SignatureDescription);
// Type RSAPKCS1SHA512SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA512SignatureDescription);
// string RIPEMD160ManagedType = "System.Security.Cryptography.RIPEMD160Managed" + AssemblyName_Encoding;
// string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyName_Cng;
// string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyName_Cng;
// string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyName_Cng;
// string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyName_Cng;
// string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyName_Cng;
// string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyName_Cng;
// string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyName_Csp;
// string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyName_Csp;
// string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyName_Csp;
// string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity;
// Xml Dsig Transforms
// First arg must match the constants defined in System.Security.Cryptography.Xml.SignedXml
// ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "System.Security.Cryptography.Xml.XmlDsigC14NTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", "System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#", "System.Security.Cryptography.Xml.XmlDsigExcC14NTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", "System.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig#base64", "System.Security.Cryptography.Xml.XmlDsigBase64Transform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/TR/1999/REC-xpath-19991116", "System.Security.Cryptography.Xml.XmlDsigXPathTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/TR/1999/REC-xslt-19991116", "System.Security.Cryptography.Xml.XmlDsigXsltTransform, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig#enveloped-signature", "System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform, " + AssemblyRef.SystemSecurity);
// the decryption transform
// ht.Add("http://www.w3.org/2002/07/decrypt#XML", "System.Security.Cryptography.Xml.XmlDecryptionTransform, " + AssemblyRef.SystemSecurity);
// Xml licence transform.
// ht.Add("urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform", "System.Security.Cryptography.Xml.XmlLicenseTransform, " + AssemblyRef.SystemSecurity);
// Xml Dsig KeyInfo
// First arg (the key) is formed as elem.NamespaceURI + " " + elem.LocalName
// ht.Add("http://www.w3.org/2000/09/xmldsig# X509Data", "System.Security.Cryptography.Xml.KeyInfoX509Data, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig# KeyName", "System.Security.Cryptography.Xml.KeyInfoName, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue", "System.Security.Cryptography.Xml.DSAKeyValue, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue", "System.Security.Cryptography.Xml.RSAKeyValue, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2000/09/xmldsig# RetrievalMethod", "System.Security.Cryptography.Xml.KeyInfoRetrievalMethod, " + AssemblyRef.SystemSecurity);
// Xml EncryptedKey
// ht.Add("http://www.w3.org/2001/04/xmlenc# EncryptedKey", "System.Security.Cryptography.Xml.KeyInfoEncryptedKey, " + AssemblyRef.SystemSecurity);
// ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160", HMACRIPEMD160Type);
}
}
public static void AddAlgorithm(Type algorithm, params string[] names)
{
throw new PlatformNotSupportedException();
}
public static object CreateFromName(string name, params object[] args)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Type retvalType = null;
// We allow the default table to Types and Strings
// Types get used for types in .Algorithms assembly.
// strings get used for delay-loaded stuff in other assemblies such as .Csp.
object retvalObj;
if (DefaultNameHT.TryGetValue(name, out retvalObj))
{
if (retvalObj is Type)
{
retvalType = (Type)retvalObj;
}
else if (retvalObj is string)
{
retvalType = Type.GetType((string)retvalObj, false, false);
if (retvalType != null && !retvalType.IsVisible)
{
retvalType = null;
}
}
else
{
Debug.Fail("Unsupported Dictionary value:" + retvalObj.ToString());
}
}
// Maybe they gave us a classname.
if (retvalType == null)
{
retvalType = Type.GetType(name, false, false);
if (retvalType != null && !retvalType.IsVisible)
{
retvalType = null;
}
}
// Still null? Then we didn't find it.
if (retvalType == null)
{
return null;
}
// Locate all constructors.
MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault);
if (cons == null)
{
return null;
}
if (args == null)
{
args = new object[] { };
}
List<MethodBase> candidates = new List<MethodBase>();
for (int i = 0; i < cons.Length; i++)
{
MethodBase con = cons[i];
if (con.GetParameters().Length == args.Length)
{
candidates.Add(con);
}
}
if (candidates.Count == 0)
{
return null;
}
cons = candidates.ToArray();
// Bind to matching ctor.
object state;
ConstructorInfo rci = Type.DefaultBinder.BindToMethod(
ConstructorDefault,
cons,
ref args,
null,
null,
null,
out state) as ConstructorInfo;
// Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand).
if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType))
{
return null;
}
// Ctor invoke and allocation.
object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null);
// Reset any parameter re-ordering performed by the binder.
if (state != null)
{
Type.DefaultBinder.ReorderArgumentArray(ref args, state);
}
return retval;
}
public static object CreateFromName(string name)
{
return CreateFromName(name, null);
}
public static void AddOID(string oid, params string[] names)
{
throw new PlatformNotSupportedException();
}
public static string MapNameToOID(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
string oidName;
if (!DefaultOidHT.TryGetValue(name, out oidName))
{
try
{
Oid oid = Oid.FromFriendlyName(name, OidGroup.All);
oidName = oid.Value;
}
catch (CryptographicException) { }
}
return oidName;
}
public static byte[] EncodeOID(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
string[] oidString = str.Split(SepArray);
uint[] oidNums = new uint[oidString.Length];
for (int i = 0; i < oidString.Length; i++)
{
oidNums[i] = unchecked((uint)int.Parse(oidString[i], CultureInfo.InvariantCulture));
}
// Handle the first two oidNums special
if (oidNums.Length < 2)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_InvalidOID);
uint firstTwoOidNums = unchecked((oidNums[0] * 40) + oidNums[1]);
// Determine length of output array
int encodedOidNumsLength = 2; // Reserve first two bytes for later
EncodeSingleOidNum(firstTwoOidNums, null, ref encodedOidNumsLength);
for (int i = 2; i < oidNums.Length; i++)
{
EncodeSingleOidNum(oidNums[i], null, ref encodedOidNumsLength);
}
// Allocate the array to receive encoded oidNums
byte[] encodedOidNums = new byte[encodedOidNumsLength];
int encodedOidNumsIndex = 2;
// Encode each segment
EncodeSingleOidNum(firstTwoOidNums, encodedOidNums, ref encodedOidNumsIndex);
for (int i = 2; i < oidNums.Length; i++)
{
EncodeSingleOidNum(oidNums[i], encodedOidNums, ref encodedOidNumsIndex);
}
Debug.Assert(encodedOidNumsIndex == encodedOidNumsLength);
// Final return value is 06 <length> encodedOidNums[]
if (encodedOidNumsIndex - 2 > 0x7f)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_Config_EncodedOIDError);
encodedOidNums[0] = (byte)0x06;
encodedOidNums[1] = (byte)(encodedOidNumsIndex - 2);
return encodedOidNums;
}
private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index)
{
// Write directly to destination starting at index, and update index based on how many bytes written.
// If destination is null, just return updated index.
if (unchecked((int)value) < 0x80)
{
if (destination != null)
{
destination[index++] = unchecked((byte)value);
}
else
{
index += 1;
}
}
else if (value < 0x4000)
{
if (destination != null)
{
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
else
{
index += 2;
}
}
else if (value < 0x200000)
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 3;
}
}
else if (value < 0x10000000)
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 21) | 0x80);
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 4;
}
}
else
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 28) | 0x80);
destination[index++] = (byte)((value >> 21) | 0x80);
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 5;
}
}
}
}
}
| |
namespace MahApps.Metro.Controls
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
/// <summary>
/// Represents a Windows spin box (also known as an up-down control) that displays numeric values.
/// </summary>
[TemplatePart(Name = ElementNumericUp, Type = typeof(RepeatButton))]
[TemplatePart(Name = ElementNumericDown, Type = typeof(RepeatButton))]
[TemplatePart(Name = ElementTextBox, Type = typeof(TextBox))]
public class NumericUpDown : Control
{
public static readonly RoutedEvent ValueIncrementedEvent = EventManager.RegisterRoutedEvent("ValueIncremented", RoutingStrategy.Bubble, typeof(NumericUpDownChangedRoutedEventHandler), typeof(NumericUpDown));
public static readonly RoutedEvent ValueDecrementedEvent = EventManager.RegisterRoutedEvent("ValueDecremented", RoutingStrategy.Bubble, typeof(NumericUpDownChangedRoutedEventHandler), typeof(NumericUpDown));
public static readonly RoutedEvent DelayChangedEvent = EventManager.RegisterRoutedEvent("DelayChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NumericUpDown));
public static readonly RoutedEvent MaximumReachedEvent = EventManager.RegisterRoutedEvent("MaximumReached", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NumericUpDown));
public static readonly RoutedEvent MinimumReachedEvent = EventManager.RegisterRoutedEvent("MinimumReached", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NumericUpDown));
public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<double?>), typeof(NumericUpDown));
public static readonly DependencyProperty DelayProperty = DependencyProperty.Register(
"Delay",
typeof(int),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(DefaultDelay, OnDelayChanged),
ValidateDelay);
public static readonly DependencyProperty TextAlignmentProperty = TextBox.TextAlignmentProperty.AddOwner(typeof(NumericUpDown));
public static readonly DependencyProperty SpeedupProperty = DependencyProperty.Register(
"Speedup",
typeof(bool),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(true, OnSpeedupChanged));
public static readonly DependencyProperty IsReadOnlyProperty = TextBoxBase.IsReadOnlyProperty.AddOwner(
typeof(NumericUpDown),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, IsReadOnlyPropertyChangedCallback));
private static void IsReadOnlyPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != e.NewValue && e.NewValue != null)
{
var numUpDown = (NumericUpDown)dependencyObject;
numUpDown.ToggleReadOnlyMode((bool)e.NewValue | !numUpDown.InterceptManualEnter);
}
}
public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register(
"StringFormat",
typeof(string),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(string.Empty, OnStringFormatChanged, CoerceStringFormat));
public static readonly DependencyProperty InterceptArrowKeysProperty = DependencyProperty.Register(
"InterceptArrowKeys",
typeof(bool),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(true));
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value",
typeof(double?),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(default(double?), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged, CoerceValue));
public static readonly DependencyProperty ButtonsAlignmentProperty = DependencyProperty.Register(
"ButtonsAlignment",
typeof(ButtonsAlignment),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(ButtonsAlignment.Right, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(
"Minimum",
typeof(double),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(double.MinValue, OnMinimumChanged));
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(
"Maximum",
typeof(double),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(double.MaxValue, OnMaximumChanged, CoerceMaximum));
public static readonly DependencyProperty IntervalProperty = DependencyProperty.Register(
"Interval",
typeof(double),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(DefaultInterval, IntervalChanged));
public static readonly DependencyProperty InterceptMouseWheelProperty = DependencyProperty.Register(
"InterceptMouseWheel",
typeof(bool),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(true));
public static readonly DependencyProperty TrackMouseWheelWhenMouseOverProperty = DependencyProperty.Register(
"TrackMouseWheelWhenMouseOver",
typeof(bool),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(default(bool)));
public static readonly DependencyProperty HideUpDownButtonsProperty = DependencyProperty.Register(
"HideUpDownButtons",
typeof(bool),
typeof(NumericUpDown),
new PropertyMetadata(default(bool)));
public static readonly DependencyProperty UpDownButtonsWidthProperty = DependencyProperty.Register(
"UpDownButtonsWidth",
typeof(double),
typeof(NumericUpDown),
new PropertyMetadata(20d));
public static readonly DependencyProperty InterceptManualEnterProperty = DependencyProperty.Register(
"InterceptManualEnter",
typeof(bool),
typeof(NumericUpDown),
new PropertyMetadata(true, InterceptManualEnterChangedCallback));
private static void InterceptManualEnterChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != e.NewValue && e.NewValue != null)
{
var numUpDown = (NumericUpDown)dependencyObject;
numUpDown.ToggleReadOnlyMode(!(bool)e.NewValue | numUpDown.IsReadOnly);
}
}
public static readonly DependencyProperty CultureProperty = DependencyProperty.Register(
"Culture",
typeof(CultureInfo),
typeof(NumericUpDown),
new PropertyMetadata(null, (o, e) => {
if (e.NewValue != e.OldValue)
{
var numUpDown = (NumericUpDown) o;
numUpDown.OnValueChanged(numUpDown.Value, numUpDown.Value);
}
}));
public static readonly DependencyProperty SelectAllOnFocusProperty = DependencyProperty.Register(
"SelectAllOnFocus",
typeof(bool),
typeof(NumericUpDown),
new PropertyMetadata(true));
public static readonly DependencyProperty HasDecimalsProperty = DependencyProperty.Register(
"HasDecimals",
typeof(bool),
typeof(NumericUpDown),
new FrameworkPropertyMetadata(true, OnHasDecimalsChanged));
private const double DefaultInterval = 1d;
private const int DefaultDelay = 500;
private const string ElementNumericDown = "PART_NumericDown";
private const string ElementNumericUp = "PART_NumericUp";
private const string ElementTextBox = "PART_TextBox";
private const string ScientificNotationChar = "E";
private const StringComparison StrComp = StringComparison.InvariantCultureIgnoreCase;
private Tuple<string, string> _removeFromText = new Tuple<string, string>(string.Empty, string.Empty);
private Lazy<PropertyInfo> _handlesMouseWheelScrolling = new Lazy<PropertyInfo>();
private double _internalIntervalMultiplierForCalculation = DefaultInterval;
private double _internalLargeChange = DefaultInterval * 100;
private double _intervalValueSinceReset;
private bool _manualChange;
private RepeatButton _repeatDown;
private RepeatButton _repeatUp;
private TextBox _valueTextBox;
private ScrollViewer _scrollViewer;
static NumericUpDown()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(typeof(NumericUpDown)));
VerticalContentAlignmentProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(VerticalAlignment.Center));
HorizontalContentAlignmentProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(HorizontalAlignment.Right));
EventManager.RegisterClassHandler(typeof(NumericUpDown), UIElement.GotFocusEvent, new RoutedEventHandler(OnGotFocus));
}
public event RoutedPropertyChangedEventHandler<double?> ValueChanged
{
add { AddHandler(ValueChangedEvent, value); }
remove { RemoveHandler(ValueChangedEvent, value); }
}
/// <summary>
/// Event fired from this NumericUpDown when its value has reached the maximum value
/// </summary>
public event RoutedEventHandler MaximumReached
{
add { AddHandler(MaximumReachedEvent, value); }
remove { RemoveHandler(MaximumReachedEvent, value); }
}
/// <summary>
/// Event fired from this NumericUpDown when its value has reached the minimum value
/// </summary>
public event RoutedEventHandler MinimumReached
{
add { AddHandler(MinimumReachedEvent, value); }
remove { RemoveHandler(MinimumReachedEvent, value); }
}
public event NumericUpDownChangedRoutedEventHandler ValueIncremented
{
add { AddHandler(ValueIncrementedEvent, value); }
remove { RemoveHandler(ValueIncrementedEvent, value); }
}
public event NumericUpDownChangedRoutedEventHandler ValueDecremented
{
add { AddHandler(ValueDecrementedEvent, value); }
remove { RemoveHandler(ValueDecrementedEvent, value); }
}
public event RoutedEventHandler DelayChanged
{
add { AddHandler(DelayChangedEvent, value); }
remove { RemoveHandler(DelayChangedEvent, value); }
}
/// <summary>
/// Gets or sets the amount of time, in milliseconds, the NumericUpDown waits while the up/down button is pressed
/// before it starts increasing/decreasing the
/// <see cref="Value" /> for the specified <see cref="Interval" /> . The value must be
/// non-negative.
/// </summary>
[Bindable(true)]
[DefaultValue(DefaultDelay)]
[Category("Behavior")]
public int Delay
{
get { return (int)GetValue(DelayProperty); }
set { SetValue(DelayProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the user can use the arrow keys <see cref="Key.Up"/> and <see cref="Key.Down"/> to change values.
/// </summary>
[Bindable(true)]
[Category("Behavior")]
[DefaultValue(true)]
public bool InterceptArrowKeys
{
get { return (bool)GetValue(InterceptArrowKeysProperty); }
set { SetValue(InterceptArrowKeysProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the user can use the mouse wheel to change values.
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
public bool InterceptMouseWheel
{
get { return (bool)GetValue(InterceptMouseWheelProperty); }
set { SetValue(InterceptMouseWheelProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control must have the focus in order to change values using the mouse wheel.
/// <remarks>
/// If the value is true then the value changes when the mouse wheel is over the control. If the value is false then the value changes only if the control has the focus. If <see cref="InterceptMouseWheel"/> is set to "false" then this property has no effect.
/// </remarks>
/// </summary>
[Category("Behavior")]
[DefaultValue(false)]
public bool TrackMouseWheelWhenMouseOver
{
get { return (bool)GetValue(TrackMouseWheelWhenMouseOverProperty); }
set { SetValue(TrackMouseWheelWhenMouseOverProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the user can enter text in the control.
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
public bool InterceptManualEnter
{
get { return (bool)GetValue(InterceptManualEnterProperty); }
set { SetValue(InterceptManualEnterProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating the culture to be used in string formatting operations.
/// </summary>
[Category("Behavior")]
[DefaultValue(null)]
public CultureInfo Culture
{
get { return (CultureInfo)GetValue(CultureProperty); }
set { SetValue(CultureProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the +/- button of the control is visible.
/// </summary>
/// <remarks>
/// If the value is false then the <see cref="Value" /> of the control can be changed only if one of the following cases is satisfied:
/// <list type="bullet">
/// <item>
/// <description><see cref="InterceptArrowKeys" /> is true.</description>
/// </item>
/// <item>
/// <description><see cref="InterceptMouseWheel" /> is true.</description>
/// </item>
/// <item>
/// <description><see cref="InterceptManualEnter" /> is true.</description>
/// </item>
/// </list>
/// </remarks>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(false)]
public bool HideUpDownButtons
{
get { return (bool)GetValue(HideUpDownButtonsProperty); }
set { SetValue(HideUpDownButtonsProperty, value); }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(20d)]
public double UpDownButtonsWidth
{
get { return (double)GetValue(UpDownButtonsWidthProperty); }
set { SetValue(UpDownButtonsWidthProperty, value); }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(ButtonsAlignment.Right)]
public Controls.ButtonsAlignment ButtonsAlignment
{
get { return (ButtonsAlignment)GetValue(ButtonsAlignmentProperty); }
set { SetValue(ButtonsAlignmentProperty, value); }
}
[Bindable(true)]
[Category("Behavior")]
[DefaultValue(DefaultInterval)]
public double Interval
{
get { return (double)GetValue(IntervalProperty); }
set { SetValue(IntervalProperty, value); }
}
[Bindable(true)]
[Category("Behavior")]
[DefaultValue(true)]
public bool SelectAllOnFocus
{
get { return (bool)GetValue(SelectAllOnFocusProperty); }
set { SetValue(SelectAllOnFocusProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the text can be changed by the use of the up or down buttons only.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(false)]
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
[Bindable(true)]
[Category("Common")]
[DefaultValue(double.MaxValue)]
public double Maximum
{
get { return (double)GetValue(MaximumProperty); }
set { SetValue(MaximumProperty, value); }
}
[Bindable(true)]
[Category("Common")]
[DefaultValue(double.MinValue)]
public double Minimum
{
get { return (double)GetValue(MinimumProperty); }
set { SetValue(MinimumProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the value to be added to or subtracted from <see cref="Value" /> remains
/// always
/// <see cref="Interval" /> or if it will increase faster after pressing the up/down button/arrow some time.
/// </summary>
[Category("Common")]
[DefaultValue(true)]
public bool Speedup
{
get { return (bool)GetValue(SpeedupProperty); }
set { SetValue(SpeedupProperty, value); }
}
/// <summary>
/// Gets or sets the formatting for the displaying <see cref="Value" />
/// </summary>
/// <remarks>
/// <see href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx"></see>
/// </remarks>
[Category("Common")]
public string StringFormat
{
get { return (string)GetValue(StringFormatProperty); }
set { SetValue(StringFormatProperty, value); }
}
/// <summary>
/// Gets or sets the horizontal alignment of the contents of the text box.
/// </summary>
[Bindable(true)]
[Category("Common")]
[DefaultValue(TextAlignment.Right)]
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
[Bindable(true)]
[Category("Common")]
[DefaultValue(null)]
public double? Value
{
get { return (double?)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private CultureInfo SpecificCultureInfo
{
get { return Culture ?? Language.GetSpecificCulture(); }
}
/// <summary>
/// Indicates if the NumericUpDown should show the decimal separator or not.
/// </summary>
[Bindable(true)]
[Category("Common")]
[DefaultValue(true)]
public bool HasDecimals
{
get { return (bool)GetValue(HasDecimalsProperty); }
set { SetValue(HasDecimalsProperty, value); }
}
/// <summary>
/// Called when this element or any below gets focus.
/// </summary>
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
// When NumericUpDown gets logical focus, select the text inside us.
NumericUpDown numericUpDown = (NumericUpDown)sender;
// If we're an editable NumericUpDown, forward focus to the TextBox element
if (!e.Handled)
{
if ((numericUpDown.InterceptManualEnter || numericUpDown.IsReadOnly) && numericUpDown._valueTextBox != null)
{
if (e.OriginalSource == numericUpDown)
{
numericUpDown._valueTextBox.Focus();
e.Handled = true;
}
else if (e.OriginalSource == numericUpDown._valueTextBox && numericUpDown.SelectAllOnFocus)
{
numericUpDown._valueTextBox.SelectAll();
}
}
}
}
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes call
/// <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_repeatUp = GetTemplateChild(ElementNumericUp) as RepeatButton;
_repeatDown = GetTemplateChild(ElementNumericDown) as RepeatButton;
_valueTextBox = GetTemplateChild(ElementTextBox) as TextBox;
if (_repeatUp == null ||
_repeatDown == null ||
_valueTextBox == null)
{
throw new InvalidOperationException(string.Format("You have missed to specify {0}, {1} or {2} in your template", ElementNumericUp, ElementNumericDown, ElementTextBox));
}
this.ToggleReadOnlyMode(this.IsReadOnly | !this.InterceptManualEnter);
_repeatUp.Click += (o, e) => ChangeValueWithSpeedUp(true);
_repeatDown.Click += (o, e) => ChangeValueWithSpeedUp(false);
_repeatUp.PreviewMouseUp += (o, e) => ResetInternal();
_repeatDown.PreviewMouseUp += (o, e) => ResetInternal();
OnValueChanged(Value, Value);
_scrollViewer = TryFindScrollViewer();
}
private void ToggleReadOnlyMode(bool isReadOnly)
{
if (_repeatUp == null || _repeatDown == null || _valueTextBox == null)
{
return;
}
if (isReadOnly)
{
_valueTextBox.LostFocus -= OnTextBoxLostFocus;
_valueTextBox.PreviewTextInput -= OnPreviewTextInput;
_valueTextBox.PreviewKeyDown -= OnTextBoxKeyDown;
_valueTextBox.TextChanged -= OnTextChanged;
DataObject.RemovePastingHandler(_valueTextBox, OnValueTextBoxPaste);
}
else
{
_valueTextBox.LostFocus += OnTextBoxLostFocus;
_valueTextBox.PreviewTextInput += OnPreviewTextInput;
_valueTextBox.PreviewKeyDown += OnTextBoxKeyDown;
_valueTextBox.TextChanged += OnTextChanged;
DataObject.AddPastingHandler(_valueTextBox, OnValueTextBoxPaste);
}
}
public void SelectAll()
{
if (_valueTextBox != null)
{
_valueTextBox.SelectAll();
}
}
protected virtual void OnDelayChanged(int oldDelay, int newDelay)
{
if (oldDelay != newDelay)
{
if (_repeatDown != null)
{
_repeatDown.Delay = newDelay;
}
if (_repeatUp != null)
{
_repeatUp.Delay = newDelay;
}
}
}
protected virtual void OnMaximumChanged(double oldMaximum, double newMaximum)
{
}
protected virtual void OnMinimumChanged(double oldMinimum, double newMinimum)
{
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (!InterceptArrowKeys)
{
return;
}
switch (e.Key)
{
case Key.Up:
ChangeValueWithSpeedUp(true);
e.Handled = true;
break;
case Key.Down:
ChangeValueWithSpeedUp(false);
e.Handled = true;
break;
}
if (e.Handled)
{
_manualChange = false;
InternalSetText(Value);
}
}
protected override void OnPreviewKeyUp(KeyEventArgs e)
{
base.OnPreviewKeyUp(e);
if (e.Key == Key.Down ||
e.Key == Key.Up)
{
ResetInternal();
}
}
protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
{
base.OnPreviewMouseWheel(e);
if (InterceptMouseWheel && (IsFocused || _valueTextBox.IsFocused || TrackMouseWheelWhenMouseOver))
{
bool increment = e.Delta > 0;
_manualChange = false;
ChangeValueInternal(increment);
}
if (_scrollViewer != null && _handlesMouseWheelScrolling.Value != null)
{
if (TrackMouseWheelWhenMouseOver)
{
_handlesMouseWheelScrolling.Value.SetValue(_scrollViewer, true, null);
}
else if (InterceptMouseWheel)
{
_handlesMouseWheelScrolling.Value.SetValue(_scrollViewer, _valueTextBox.IsFocused, null);
}
else
{
_handlesMouseWheelScrolling.Value.SetValue(_scrollViewer, true, null);
}
}
}
protected void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = true;
if (string.IsNullOrWhiteSpace(e.Text) ||
e.Text.Length != 1)
{
return;
}
string text = e.Text;
if (char.IsDigit(text[0]))
{
e.Handled = false;
}
else
{
CultureInfo equivalentCulture = SpecificCultureInfo;
NumberFormatInfo numberFormatInfo = equivalentCulture.NumberFormat;
TextBox textBox = (TextBox)sender;
bool allTextSelected = textBox.SelectedText == textBox.Text;
if (numberFormatInfo.NumberDecimalSeparator == text)
{
if (textBox.Text.All(i => i.ToString(equivalentCulture) != numberFormatInfo.NumberDecimalSeparator) || allTextSelected)
{
if (HasDecimals)
{
e.Handled = false;
}
}
}
else
{
if (numberFormatInfo.NegativeSign == text ||
text == numberFormatInfo.PositiveSign)
{
if (textBox.SelectionStart == 0)
{
// check if text already has a + or - sign
if (textBox.Text.Length > 1)
{
if (allTextSelected ||
(!textBox.Text.StartsWith(numberFormatInfo.NegativeSign, StrComp) &&
!textBox.Text.StartsWith(numberFormatInfo.PositiveSign, StrComp)))
{
e.Handled = false;
}
}
else
{
e.Handled = false;
}
}
else if (textBox.SelectionStart > 0)
{
string elementBeforeCaret = textBox.Text.ElementAt(textBox.SelectionStart - 1).ToString(equivalentCulture);
if (elementBeforeCaret.Equals(ScientificNotationChar, StrComp))
{
e.Handled = false;
}
}
}
else if (text.Equals(ScientificNotationChar, StrComp) &&
textBox.SelectionStart > 0 &&
!textBox.Text.Any(i => i.ToString(equivalentCulture).Equals(ScientificNotationChar, StrComp)))
{
e.Handled = false;
}
}
}
}
protected virtual void OnSpeedupChanged(bool oldSpeedup, bool newSpeedup)
{
}
/// <summary>
/// Raises the <see cref="ValueChanged" /> routed event.
/// </summary>
/// <param name="oldValue">
/// Old value of the <see cref="Value" /> property
/// </param>
/// <param name="newValue">
/// New value of the <see cref="Value" /> property
/// </param>
protected virtual void OnValueChanged(double? oldValue, double? newValue)
{
if (!_manualChange)
{
if (!newValue.HasValue)
{
if (_valueTextBox != null)
{
_valueTextBox.Text = null;
}
if (oldValue != newValue)
{
this.RaiseEvent(new RoutedPropertyChangedEventArgs<double?>(oldValue, newValue, ValueChangedEvent));
}
return;
}
if (_repeatUp != null && !_repeatUp.IsEnabled)
{
_repeatUp.IsEnabled = true;
}
if (_repeatDown != null && !_repeatDown.IsEnabled)
{
_repeatDown.IsEnabled = true;
}
if (newValue <= Minimum)
{
if (_repeatDown != null)
{
_repeatDown.IsEnabled = false;
}
ResetInternal();
if (IsLoaded)
{
RaiseEvent(new RoutedEventArgs(MinimumReachedEvent));
}
}
if (newValue >= Maximum)
{
if (_repeatUp != null)
{
_repeatUp.IsEnabled = false;
}
ResetInternal();
if (IsLoaded)
{
RaiseEvent(new RoutedEventArgs(MaximumReachedEvent));
}
}
if (_valueTextBox != null)
{
InternalSetText(newValue);
}
}
if (oldValue != newValue)
{
this.RaiseEvent(new RoutedPropertyChangedEventArgs<double?>(oldValue, newValue, ValueChangedEvent));
}
}
private static object CoerceMaximum(DependencyObject d, object value)
{
double minimum = ((NumericUpDown)d).Minimum;
double val = (double)value;
return val < minimum ? minimum : val;
}
private static object CoerceStringFormat(DependencyObject d, object basevalue)
{
return basevalue ?? string.Empty;
}
private static object CoerceValue(DependencyObject d, object value)
{
if (value == null)
{
return null;
}
var numericUpDown = (NumericUpDown)d;
double val = ((double?)value).Value;
if (numericUpDown.HasDecimals == false)
{
val = Math.Truncate(val);
}
if (val < numericUpDown.Minimum)
{
return numericUpDown.Minimum;
}
if (val > numericUpDown.Maximum)
{
return numericUpDown.Maximum;
}
return val;
}
private static void IntervalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var numericUpDown = (NumericUpDown)d;
numericUpDown.ResetInternal();
}
private static void OnDelayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NumericUpDown ctrl = (NumericUpDown)d;
ctrl.RaiseChangeDelay();
ctrl.OnDelayChanged((int)e.OldValue, (int)e.NewValue);
}
private static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var numericUpDown = (NumericUpDown)d;
numericUpDown.CoerceValue(ValueProperty);
numericUpDown.OnMaximumChanged((double)e.OldValue, (double)e.NewValue);
numericUpDown.EnableDisableUpDown();
}
private static void OnMinimumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var numericUpDown = (NumericUpDown)d;
numericUpDown.CoerceValue(ValueProperty);
numericUpDown.CoerceValue(MaximumProperty);
numericUpDown.OnMinimumChanged((double)e.OldValue, (double)e.NewValue);
numericUpDown.EnableDisableUpDown();
}
private static void OnSpeedupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NumericUpDown ctrl = (NumericUpDown)d;
ctrl.OnSpeedupChanged((bool)e.OldValue, (bool)e.NewValue);
}
private static void OnStringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NumericUpDown nud = (NumericUpDown)d;
nud.SetRemoveStringFormatFromText((string)e.NewValue);
if (nud._valueTextBox != null &&
nud.Value.HasValue)
{
nud.InternalSetText(nud.Value);
}
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var numericUpDown = (NumericUpDown)d;
numericUpDown.OnValueChanged((double?)e.OldValue, (double?)e.NewValue);
}
private static void OnHasDecimalsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var numericUpDown = (NumericUpDown)d;
double? oldValue = numericUpDown.Value;
if ((bool)e.NewValue == false && numericUpDown.Value != null)
{
numericUpDown.Value = Math.Truncate(numericUpDown.Value.GetValueOrDefault());
}
}
private static bool ValidateDelay(object value)
{
return Convert.ToInt32(value) >= 0;
}
private void InternalSetText(double? newValue)
{
if (!newValue.HasValue)
{
_valueTextBox.Text = null;
return;
}
CultureInfo culture = SpecificCultureInfo;
if (string.IsNullOrEmpty(StringFormat))
{
_valueTextBox.Text = newValue.Value.ToString(culture);
}
else if (!StringFormat.Contains("{"))
{
// then we may have a StringFormat of e.g. "N0"
_valueTextBox.Text = newValue.Value.ToString(StringFormat, culture);
}
else
{
_valueTextBox.Text = string.Format(culture, StringFormat, newValue.Value);
}
if ((bool)GetValue(TextBoxHelper.IsMonitoringProperty))
{
SetValue(TextBoxHelper.TextLengthProperty, _valueTextBox.Text.Length);
}
}
private ScrollViewer TryFindScrollViewer()
{
_valueTextBox.ApplyTemplate();
var scrollViewer = _valueTextBox.Template.FindName("PART_ContentHost", _valueTextBox) as ScrollViewer;
if (scrollViewer != null)
{
_handlesMouseWheelScrolling = new Lazy<PropertyInfo>(() => _scrollViewer.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).SingleOrDefault(i => i.Name == "HandlesMouseWheelScrolling"));
}
return scrollViewer;
}
private void ChangeValueWithSpeedUp(bool toPositive)
{
if (IsReadOnly)
{
return;
}
double direction = toPositive ? 1 : -1;
if (Speedup)
{
double d = Interval * _internalLargeChange;
if ((_intervalValueSinceReset += Interval * _internalIntervalMultiplierForCalculation) > d)
{
_internalLargeChange *= 10;
_internalIntervalMultiplierForCalculation *= 10;
}
ChangeValueInternal(direction * _internalIntervalMultiplierForCalculation);
}
else
{
ChangeValueInternal(direction * Interval);
}
}
private void ChangeValueInternal(bool addInterval)
{
ChangeValueInternal(addInterval ? Interval : -Interval);
}
private void ChangeValueInternal(double interval)
{
if (IsReadOnly)
{
return;
}
NumericUpDownChangedRoutedEventArgs routedEvent = interval > 0 ?
new NumericUpDownChangedRoutedEventArgs(ValueIncrementedEvent, interval) :
new NumericUpDownChangedRoutedEventArgs(ValueDecrementedEvent, interval);
RaiseEvent(routedEvent);
if (!routedEvent.Handled)
{
ChangeValueBy(routedEvent.Interval);
_valueTextBox.CaretIndex = _valueTextBox.Text.Length;
}
}
private void ChangeValueBy(double difference)
{
double newValue = Value.GetValueOrDefault() + difference;
Value = (double)CoerceValue(this, newValue);
}
private void EnableDisableDown()
{
if (_repeatDown != null)
{
_repeatDown.IsEnabled = Value > Minimum;
}
}
private void EnableDisableUp()
{
if (_repeatUp != null)
{
_repeatUp.IsEnabled = Value < Maximum;
}
}
private void EnableDisableUpDown()
{
EnableDisableUp();
EnableDisableDown();
}
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
_manualChange = true;
}
private void OnTextBoxLostFocus(object sender, RoutedEventArgs e)
{
if (!InterceptManualEnter)
{
return;
}
TextBox tb = (TextBox)sender;
_manualChange = false;
double convertedValue;
if (ValidateText(tb.Text, out convertedValue))
{
if (Value == convertedValue)
{
OnValueChanged(Value, Value);
}
if (convertedValue > Maximum)
{
if (Value == Maximum)
{
OnValueChanged(Value, Value);
}
else
{
SetValue(ValueProperty, Maximum);
}
}
else if (convertedValue < Minimum)
{
if (Value == Minimum)
{
OnValueChanged(Value, Value);
}
else
{
SetValue(ValueProperty, Minimum);
}
}
else
{
SetValue(ValueProperty, convertedValue);
}
}
else
{
OnValueChanged(Value, Value);
}
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(((TextBox)sender).Text))
{
Value = null;
}
else if (_manualChange)
{
double convertedValue;
if (ValidateText(((TextBox)sender).Text, out convertedValue))
{
Value = (double?)CoerceValue(this, convertedValue);
e.Handled = true;
}
}
}
private void OnValueTextBoxPaste(object sender, DataObjectPastingEventArgs e)
{
var textBox = (TextBox)sender;
string textPresent = textBox.Text;
var isText = e.SourceDataObject.GetDataPresent(DataFormats.Text, true);
if (!isText)
{
return;
}
var text = e.SourceDataObject.GetData(DataFormats.Text) as string;
string newText = string.Concat(textPresent.Substring(0, textBox.SelectionStart), text, textPresent.Substring(textBox.SelectionStart));
double number;
if (!ValidateText(newText, out number))
{
e.CancelCommand();
}
}
private void RaiseChangeDelay()
{
RaiseEvent(new RoutedEventArgs(DelayChangedEvent));
}
private void ResetInternal()
{
if (IsReadOnly)
{
return;
}
_internalLargeChange = 100 * Interval;
_internalIntervalMultiplierForCalculation = Interval;
_intervalValueSinceReset = 0;
}
private bool ValidateText(string text, out double convertedValue)
{
text = RemoveStringFormatFromText(text);
return double.TryParse(text, NumberStyles.Any, SpecificCultureInfo, out convertedValue);
}
private string RemoveStringFormatFromText(string text)
{
// remove special string formattings in order to be able to parse it to double e.g. StringFormat = "{0:N2} pcs." then remove pcs. from text
if (!string.IsNullOrEmpty(_removeFromText.Item1))
{
text = text.Replace(_removeFromText.Item1, string.Empty);
}
if (!string.IsNullOrEmpty(_removeFromText.Item2))
{
text = text.Replace(_removeFromText.Item2, string.Empty);
}
return text;
}
private void SetRemoveStringFormatFromText(string stringFormat)
{
string tailing = string.Empty;
string leading = string.Empty;
string format = stringFormat;
int indexOf = format.IndexOf("{", StrComp);
if (indexOf > -1)
{
if (indexOf > 0)
{
// remove beginning e.g.
// pcs. from "pcs. {0:N2}"
tailing = format.Substring(0, indexOf);
}
// remove tailing e.g.
// pcs. from "{0:N2} pcs."
leading = new string(format.SkipWhile(i => i != '}').Skip(1).ToArray()).Trim();
}
_removeFromText = new Tuple<string, string>(tailing, leading);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Maetsilor.Data;
using Maetsilor.Models;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Maetsilor.Models.MatchMakingViewModel;
using Microsoft.EntityFrameworkCore;
namespace Maetsilor.Controllers
{
public class MatchMakingController : Controller
{
private ApplicationDbContext _context = null;
private readonly UserManager<ApplicationUser> _userManager;
public MatchMakingController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: MatchMaking
public ActionResult Index()
{
ApplicationUser user = _context.Users.First(u => u.UserName == HttpContext.User.Identity.Name);
List<Group> groups = _context.Groups.ToList();
List<int> userGroups = new List<int>();
foreach(Group g in groups)
{
if(_context.UserGroups.Any(ug => ug.GroupID == g.ID && ug.UserID == user.Id))
{
userGroups.Add(g.ID);
}
}
ViewData["UserGroups"] = userGroups;
return View(groups);
}
// GET: MatchMaking
public ActionResult IndexUserGroups()
{
ApplicationUser user = _context.Users.First(u => u.UserName == HttpContext.User.Identity.Name);
if (user == null)
{
return View("Error");
}
List<Group> groups = new List<Group>();
foreach (UserGroup ug in _context.UserGroups)
{
if (ug.UserID == user.Id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == ug.GroupID);
groups.Add(g);
}
}
return View(groups);
}
// GET: MatchMaking/Details/5
public ActionResult Details(int id)
{
Group g = _context.Groups.Where(gr => gr.ID == id).Single();
return View(g);
}
// GET: MatchMaking/Create
public ActionResult Create()
{
return View("Create");
}
// POST: MatchMaking/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
ApplicationUser user = _context.Users.First(u => u.UserName == HttpContext.User.Identity.Name);
if (user == null)
{
return View("Error");
}
Group g = new Group();
TryUpdateModelAsync(g);
g.MaitreDuJeu = user.UserName;
g.ID = 0;
g.Membres = new List<ApplicationUser>();
g.Chat = new List<ChatMessage>();
g.Membres.Add(user);
_context.Add(g);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: MatchMaking/IndexMembre/5
public ActionResult IndexMembre(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
List<Membre> lm = new List<Membre>();
foreach (UserGroup ug in _context.UserGroups)
{
if (ug.GroupID == g.ID && ug.IsMember)
{
ApplicationUser user = _context.Users.FirstOrDefault(u => u.Id == ug.UserID);
Membre m = new Membre(user);
lm.Add(m);
}
}
ViewData["GroupID"] = id;
ViewData["GroupMaster"] = g.MaitreDuJeu;
return View(lm);
}
// GET: MatchMaking/IndexDemandes
public ActionResult IndexDemandes(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
List<Membre> lm = new List<Membre>();
foreach (UserGroup ug in _context.UserGroups)
{
if (ug.GroupID == g.ID && !ug.IsMember)
{
ApplicationUser user = _context.Users.FirstOrDefault(u => u.Id == ug.UserID);
Membre m = new Membre(user);
lm.Add(m);
}
}
ViewData["GroupID"] = id;
ViewData["GroupMaster"] = g.MaitreDuJeu;
return View(lm);
}
// GET: MatchMaking/Chat
public ActionResult Chat(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
List<ChatMessage> lm = new List<ChatMessage>();
foreach (ChatMessage c in _context.ChatMessages.ToList())
{
if (c.GroupID == g.ID)
{
lm.Add(c);
}
}
ViewData["GroupID"] = id;
ViewData["GroupMaster"] = g.MaitreDuJeu;
return View(lm);
}
// GET: MatchMaking/ChatReply
public ActionResult ChatReply(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
ViewData["GroupID"] = id;
return View();
}
// POST: MatchMaking/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChatReply(ChatMessage reply)
{
try
{
ApplicationUser user = _context.Users.First(u => u.UserName == HttpContext.User.Identity.Name);
if (user == null)
{
return View("Error");
}
ChatMessage m = new ChatMessage();
m.Auteur = user.ToString();
m.Date = DateTime.UtcNow;
m.Message = reply.Message;
m.GroupID = reply.ID;
_context.ChatMessages.Add(m);
_context.SaveChanges();
return RedirectToAction("Chat", new { id = reply.ID });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
// GET: MatchMaking/Edit/5
public ActionResult Edit(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
return View(g);
}
// POST: MatchMaking/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
TryUpdateModelAsync(g);
_context.SaveChanges();
return RedirectToAction("Details", new { id = g.ID });
}
catch
{
return View();
}
}
// GET: MatchMaking/Delete/5
public ActionResult Delete(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
return View(g);
}
// POST: MatchMaking/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
Group g = _context.Groups.Where(gr => gr.ID == id).Single();
_context.Groups.Remove(g);
_context.SaveChanges();
return RedirectToAction("IndexUserGroups");
}
catch
{
return RedirectToAction("Index");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Join(int id, IFormCollection collection)
{
try
{
ApplicationUser user = _context.Users.First(u => u.UserName == HttpContext.User.Identity.Name);
if (user == null)
{
return View("Error");
}
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
UserGroup ug = new UserGroup();
ug.GroupID = g.ID;
ug.UserID = user.Id;
ug.IsMember = false;
_context.Add(ug);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult KickMember(int id, string memberId)
{
try
{
UserGroup ug = _context.UserGroups.FirstOrDefault(u => u.GroupID == id && u.UserID == memberId);
_context.Remove(ug);
_context.SaveChanges();
return RedirectToAction("IndexMembre", new { id = id });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
// GET: MatchMaking/IndexCalendrier
public ActionResult IndexCalendrier(int id)
{
Group g = _context.Groups.FirstOrDefault(gr => gr.ID == id);
ViewData["GroupID"] = id;
ViewData["GroupMaster"] = g.MaitreDuJeu;
List<Partie> lp = new List<Partie>();
foreach (Partie p in _context.Parties)
{
if (p.GroupID == g.ID)
{
lp.Add(p);
}
}
return View(lp);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CancelPartie(int id, int partieId)
{
Partie partie = _context.Parties.FirstOrDefault(p => p.ID == partieId);
try
{
_context.Remove(partie);
_context.SaveChanges();
return RedirectToAction("IndexCalendrier", new { id = id });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeclineMember(int id, string memberId)
{
try
{
UserGroup ug = _context.UserGroups.FirstOrDefault(u => u.GroupID == id && u.UserID == memberId);
_context.Remove(ug);
_context.SaveChanges();
return RedirectToAction("IndexDemandes", new { id = id });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AcceptMember(int id, string memberId)
{
try
{
UserGroup ug = _context.UserGroups.FirstOrDefault(u => u.GroupID == id && u.UserID == memberId);
ug.IsMember = true;
_context.Update(ug);
_context.SaveChanges();
return RedirectToAction("IndexDemandes", new { id = id });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
public ActionResult CreatePartie(int id)
{
ViewData["GroupID"] = id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreatePartie(int id, Partie partie)
{
try
{
Partie p = new Partie();
p.Date = partie.Date;
p.Description = partie.Description;
p.GroupID = id;
_context.Parties.Add(p);
_context.SaveChanges();
return RedirectToAction("IndexCalendrier", new { id = id });
}
catch
{
return RedirectToAction("Index", "Home");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Maps;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Engine.Basics;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Entities;
using Signum.Engine.Operations;
using System.Reflection;
using System.Xml.Linq;
using System.Collections.Immutable;
namespace Signum.Engine.Authorization
{
public static class OperationAuthLogic
{
static AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed> cache = null!;
public static IManualAuth<(OperationSymbol operation, Type type), OperationAllowed> Manual { get { return cache; } }
public static bool IsStarted { get { return cache != null; } }
public static readonly Dictionary<OperationSymbol, MinimumTypeAllowed> MinimumTypeAllowed = new Dictionary<OperationSymbol, MinimumTypeAllowed>();
public static readonly Dictionary<OperationSymbol, OperationAllowed> MaxAutomaticUpgrade = new Dictionary<OperationSymbol, OperationAllowed>();
internal static readonly string operationReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
AuthLogic.AssertStarted(sb);
OperationLogic.AssertStarted(sb);
OperationLogic.AllowOperation += OperationLogic_AllowOperation;
sb.Include<RuleOperationEntity>()
.WithUniqueIndex(rt => new { rt.Resource.Operation, rt.Resource.Type, rt.Role });
cache = new AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed>(sb,
toKey: s => (operation: s.Operation, type: s.Type.ToType()),
toEntity: s => new OperationTypeEmbedded { Operation = s.operation, Type = s.type.ToTypeEntity() },
isEquals: (o1, o2) => o1.Operation == o2.Operation && o1.Type == o2.Type,
merger: new OperationMerger(),
invalidateWithTypes: true,
coercer: OperationCoercer.Instance);
sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query =>
{
Database.Query<RuleOperationEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
return null;
};
AuthLogic.ExportToXml += exportAll => cache.ExportXml("Operations", "Operation", s => s.operation.Key + "/" + s.type?.ToTypeEntity().CleanName, b => b.ToString(),
exportAll ? AllOperationTypes() : null);
AuthLogic.ImportFromXml += (x, roles, replacements) =>
{
var allResources = x.Element("Operations")!.Elements("Role").SelectMany(r => r.Elements("Operation")).Select(p => p.Attribute("Resource")!.Value).ToHashSet();
replacements.AskForReplacements(
allResources.Select(a => a.TryBefore("/") ?? a).ToHashSet(),
SymbolLogic<OperationSymbol>.AllUniqueKeys(),
operationReplacementKey);
string typeReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
replacements.AskForReplacements(
allResources.Select(a => a.After("/")).ToHashSet(),
TypeLogic.NameToType.Keys.ToHashSet(),
TypeAuthCache.typeReplacementKey);
return cache.ImportXml(x, "Operations", "Operation", roles,
s => {
var operation = SymbolLogic<OperationSymbol>.TryToSymbol(replacements.Apply(operationReplacementKey, s.Before("/")));
var type = TypeLogic.TryGetType(replacements.Apply(TypeAuthCache.typeReplacementKey, s.After("/")));
if (operation == null || type == null || !OperationLogic.IsDefined(type, operation))
return null;
return new OperationTypeEmbedded { Operation = operation, Type = type.ToTypeEntity() };
}, EnumExtensions.ToEnum<OperationAllowed>);
};
sb.Schema.Table<OperationSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteOperationSqlSync);
sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteTypeSqlSync);
}
}
static SqlPreCommand AuthCache_PreDeleteOperationSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Operation, (OperationSymbol)arg);
}
static SqlPreCommand AuthCache_PreDeleteTypeSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Type, (TypeEntity)arg);
}
public static T SetMaxAutomaticUpgrade<T>(this T operation, OperationAllowed allowed) where T : IOperation
{
MaxAutomaticUpgrade.Add(operation.OperationSymbol, allowed);
return operation;
}
static bool OperationLogic_AllowOperation(OperationSymbol operationKey, Type entityType, bool inUserInterface)
{
return GetOperationAllowed(operationKey, entityType, inUserInterface);
}
public static OperationRulePack GetOperationRules(Lite<RoleEntity> role, TypeEntity typeEntity)
{
var entityType = typeEntity.ToType();
var resources = OperationLogic.GetAllOperationInfos(entityType).Select(a => new OperationTypeEmbedded { Operation = a.OperationSymbol, Type = typeEntity });
var result = new OperationRulePack { Role = role, Type = typeEntity, };
cache.GetRules(result, resources);
var coercer = OperationCoercer.Instance.GetCoerceValue(role);
result.Rules.ForEach(r =>
{
var operationType = (operation: r.Resource.Operation, type: r.Resource.Type.ToType());
r.CoercedValues = EnumExtensions.GetValues<OperationAllowed>().Where(a => !coercer(operationType, a).Equals(a)).ToArray();
});
return result;
}
public static void SetOperationRules(OperationRulePack rules)
{
cache.SetRules(rules, r => r.Type == rules.Type);
}
public static bool GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType, bool inUserInterface)
{
OperationAllowed allowed = GetOperationAllowed(role, operation, entityType);
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static OperationAllowed GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType)
{
return cache.GetAllowed(role, (operation, entityType));
}
public static bool GetOperationAllowed(OperationSymbol operation, Type type, bool inUserInterface)
{
if (!AuthLogic.IsEnabled || ExecutionMode.InGlobal)
return true;
if (GetTemporallyAllowed(operation))
return true;
OperationAllowed allowed = cache.GetAllowed(RoleEntity.Current, (operation, type));
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static AuthThumbnail? GetAllowedThumbnail(Lite<RoleEntity> role, Type entityType)
{
return OperationLogic.GetAllOperationInfos(entityType).Select(oi => cache.GetAllowed(role, (oi.OperationSymbol, entityType))).Collapse();
}
public static Dictionary<(OperationSymbol operation, Type type), OperationAllowed> AllowedOperations()
{
return AllOperationTypes().ToDictionary(a => a, a => cache.GetAllowed(RoleEntity.Current, a));
}
static List<(OperationSymbol operation, Type type)> AllOperationTypes()
{
return (from type in Schema.Current.Tables.Keys
from o in OperationLogic.TypeOperations(type)
select (operation: o.OperationSymbol, type: type))
.ToList();
}
static readonly Variable<ImmutableStack<OperationSymbol>> tempAllowed = Statics.ThreadVariable<ImmutableStack<OperationSymbol>>("authTempOperationsAllowed");
public static IDisposable AllowTemporally(OperationSymbol operationKey)
{
tempAllowed.Value = (tempAllowed.Value ?? ImmutableStack<OperationSymbol>.Empty).Push(operationKey);
return new Disposable(() => tempAllowed.Value = tempAllowed.Value.Pop());
}
internal static bool GetTemporallyAllowed(OperationSymbol operationKey)
{
var ta = tempAllowed.Value;
if (ta == null || ta.IsEmpty)
return false;
return ta.Contains(operationKey);
}
public static T SetMinimumTypeAllowed<T>(this T operation, TypeAllowedBasic? overridenType, TypeAllowedBasic? returnType = null) where T : IOperation
{
MinimumTypeAllowed.Add(operation.OperationSymbol, new MinimumTypeAllowed { OverridenType = overridenType, ReturnType = returnType });
return operation;
}
public static OperationAllowed InferredOperationAllowed((OperationSymbol operation, Type type) operationType, Func<Type, TypeAllowedAndConditions> allowed)
{
Func<Type, TypeAllowedBasic, OperationAllowed> operationAllowed = (t, checkFor) =>
{
if (!TypeLogic.TypeToEntity.ContainsKey(t))
return OperationAllowed.Allow;
var ta = allowed(t);
return checkFor <= ta.MaxUI() ? OperationAllowed.Allow :
checkFor <= ta.MaxDB() ? OperationAllowed.DBOnly :
OperationAllowed.None;
};
var operation = OperationLogic.FindOperation(operationType.type ?? /*Temp*/ OperationLogic.FindTypes(operationType.operation).First(), operationType.operation);
var mta = OperationAuthLogic.MinimumTypeAllowed.TryGetC(operationType.operation);
switch (operation.OperationType)
{
case OperationType.Execute:
case OperationType.Delete:
return operationAllowed(operation.OverridenType, mta?.OverridenType ?? TypeAllowedBasic.Write);
case OperationType.Constructor:
return operationAllowed(operation.ReturnType!, mta?.ReturnType ?? TypeAllowedBasic.Write);
case OperationType.ConstructorFrom:
case OperationType.ConstructorFromMany:
{
var fromTypeAllowed = operationAllowed(operation.OverridenType, mta?.OverridenType ?? TypeAllowedBasic.Read);
var returnTypeAllowed = operationAllowed(operation.ReturnType!, mta?.ReturnType ?? TypeAllowedBasic.Write);
return returnTypeAllowed < fromTypeAllowed ? returnTypeAllowed : fromTypeAllowed;
}
default:
throw new UnexpectedValueException(operation.OperationType);
}
}
}
class OperationMerger : IMerger<(OperationSymbol operation, Type type), OperationAllowed>
{
public OperationAllowed Merge((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role, IEnumerable<KeyValuePair<Lite<RoleEntity>, OperationAllowed>> baseValues)
{
OperationAllowed best = AuthLogic.GetMergeStrategy(role) == MergeStrategy.Union ?
Max(baseValues.Select(a => a.Value)):
Min(baseValues.Select(a => a.Value));
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return best;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(operationType.Item1);
if (maxUp.HasValue && maxUp <= best)
return best;
if (baseValues.Where(a => a.Value.Equals(best)).All(a => GetDefault(operationType, a.Key).Equals(a.Value)))
{
var def = GetDefault(operationType, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
}
return best;
}
static OperationAllowed GetDefault((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role)
{
return OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.GetAllowed(role, t));
}
static OperationAllowed Max(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.None;
foreach (var item in baseValues)
{
if (item > result)
result = item;
if (result == OperationAllowed.Allow)
return result;
}
return result;
}
static OperationAllowed Min(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.Allow;
foreach (var item in baseValues)
{
if (item < result)
result = item;
if (result == OperationAllowed.None)
return result;
}
return result;
}
public Func<(OperationSymbol operation, Type type), OperationAllowed> MergeDefault(Lite<RoleEntity> role)
{
return key =>
{
if (AuthLogic.GetDefaultAllowed(role))
return OperationAllowed.Allow;
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return OperationAllowed.None;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(key.operation);
var def = GetDefault(key, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
};
}
}
public class MinimumTypeAllowed
{
public TypeAllowedBasic? OverridenType;
public TypeAllowedBasic? ReturnType;
}
class OperationCoercer : Coercer<OperationAllowed, (OperationSymbol symbol, Type type)>
{
public static readonly OperationCoercer Instance = new OperationCoercer();
private OperationCoercer()
{
}
public override Func<(OperationSymbol symbol, Type type), OperationAllowed, OperationAllowed> GetCoerceValue(Lite<RoleEntity> role)
{
return (operationType, allowed) =>
{
var required = OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
public override Func<Lite<RoleEntity>, OperationAllowed, OperationAllowed> GetCoerceValueManual((OperationSymbol symbol, Type type) operationType)
{
return (role, allowed) =>
{
var required = OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.Manual.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
}
}
| |
// 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.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.UnitTesting;
using Xunit;
namespace System.ComponentModel.Composition
{
public class AdvancedValueComposition
{
[Fact]
public void RepeatedContainerUse()
{
var container = ContainerFactory.Create();
TrivialExporter e = new TrivialExporter();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(e);
container.Compose(batch);
batch = new CompositionBatch();
batch.AddPart(new TrivialImporter());
container.Compose(batch);
Assert.True(e.done, "Initialization of importer should have set the done flag on E");
}
[Fact]
public void FunctionsFieldsAndProperties()
{
Consumer c;
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new RealAddProvider());
batch.AddPart(c = new Consumer());
container.Compose(batch);
Assert.Equal(3, c.op(c.a, c.b));
}
[Fact]
public void FunctionsFieldsAndProperties2()
{
Consumer c;
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new SubtractProvider());
batch.AddPart(c = new Consumer());
container.Compose(batch);
Assert.Equal(-1, c.op(c.a, c.b));
}
[Fact]
[ActiveIssue(25498)]
public void FunctionsFieldsAndProperties2_WithCatalog()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
ConsumerOfMultiple c = new ConsumerOfMultiple();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(c);
container.Compose(batch);
foreach (Lazy<Func<int,int,int>, IDictionary<string, object>> export in c.opInfo)
{
if ((string)export.Metadata["Var1"] == "add")
{
Assert.Equal(3, export.Value(1, 2));
}
else if ((string)export.Metadata["Var1"] == "sub")
{
Assert.Equal(-1, export.Value(1, 2));
}
else
{
throw new NotImplementedException();
}
}
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var exports = container.GetExports<Func<int, int, int>, ITrans_ExportableTest>("Add");
foreach (var export in exports)
{
if (export.Metadata.Var1 == "add")
{
Assert.Equal(3, export.Value(1, 2));
}
else if (export.Metadata.Var1 == "sub")
{
Assert.Equal(-1, export.Value(1, 2));
}
else
{
throw new NotImplementedException();
}
}
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void InAdditionToCatalogTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
IDictionary<string, object> multMetadata = new Dictionary<string, object>();
multMetadata["Var1"] = "mult";
multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func<int, int, int>));
var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func<int, int, int>)delegate (int a, int b)
{ return a * b; }));
CompositionBatch batch = new CompositionBatch();
batch.AddExport(basicValue);
container.Compose(batch);
var exports = container.GetExports<Func<int, int, int>, ITrans_ExportableTest>("Add");
Assert.Equal(3, exports.Count());
foreach (var export in exports)
{
if (export.Metadata.Var1 == "mult")
{
Assert.Equal(2, export.Value(1, 2));
}
else if (export.Metadata.Var1 == "add")
{
Assert.Equal(3, export.Value(1, 2));
}
else if (export.Metadata.Var1 == "sub")
{
Assert.Equal(-1, export.Value(1, 2));
}
else
{
throw new NotImplementedException();
}
}
}
[Fact]
[ActiveIssue(25498)]
public void CollectionMetadataPropertyTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var export = container.GetExport<ComponentWithCollectionProperty, ITrans_CollectionOfStrings>();
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Values);
Assert.Equal(export.Metadata.Values.Count(), 3);
Assert.Equal(export.Metadata.Values.First(), "One");
Assert.Equal(export.Metadata.Values.Skip(1).First(), "two");
Assert.Equal(export.Metadata.Values.Skip(2).First(), "3");
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportExportSansNameTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
UnnamedImportAndExport unnamed = container.GetExportedValue<UnnamedImportAndExport>();
Assert.NotNull(unnamed);
Assert.NotNull(unnamed.ImportedValue);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void MultipleInstantiationOfStaticCatalogItem()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var unnamedVI = container.GetExport<StaticExport, object>();
StaticExport first = unnamedVI.Value;
StaticExport second = unnamedVI.Value;
Assert.NotNull(first);
Assert.NotNull(second);
Assert.True(object.ReferenceEquals(first, second), "Instances should be the same");
var exports = container.GetExports<StaticExport, object>();
Assert.Equal(1, exports.Count());
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void MultipleInstantiationOfNonStaticCatalogItem()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var export1 = container.GetExport<NonStaticExport, object>();
var export2 = container.GetExport<NonStaticExport, object>();
NonStaticExport first = export1.Value;
NonStaticExport second = export2.Value;
Assert.NotNull(first);
Assert.NotNull(second);
Assert.False(object.ReferenceEquals(first, second), "Instances should be different");
}
[Fact]
[ActiveIssue(25498)]
public void ImportIntoUntypedExportTest()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue("untyped", 42);
var u = new UntypedExportImporter();
var rb = AttributedModelServices.CreatePart(u);
batch.AddPart(rb);
container.Compose(batch);
Assert.Equal(42, u.Export.Value);
var us = new UntypedExportsImporter();
batch = new CompositionBatch();
batch.AddExportedValue("untyped", 19);
batch.RemovePart(rb);
batch.AddPart(us);
container.Compose(batch);
Assert.NotNull(us.Exports);
Assert.Equal(2, us.Exports.Count());
}
[Fact]
public void ImportIntoDerivationOfExportException()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue("derived", typeof(DerivedExport), 42);
var d = new DerivedExportImporter();
batch.AddPart(d);
CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotSetImport,
ErrorId.ReflectionModel_ImportNotAssignableFromExport, RetryMode.DoNotRetry, () =>
{
container.Compose(batch);
});
}
[Fact]
public void ImportIntoDerivationOfExportsException()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue("derived", typeof(DerivedExport), 42);
var d = new DerivedExportsImporter();
batch.AddPart(d);
CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotSetImport,
ErrorId.ReflectionModel_ImportNotAssignableFromExport, RetryMode.DoNotRetry, () =>
{
container.Compose(batch);
});
}
}
}
| |
using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public abstract partial class PropertyStates
{
public abstract Tags Tag { get; }
public bool IsBooleanValue { get { return this.Tag == Tags.BooleanValue; } }
public bool AsBooleanValue { get { return ((BooleanValueWrapper)this).Item; } }
public static PropertyStates NewBooleanValue(bool booleanValue)
{
return new BooleanValueWrapper(booleanValue);
}
public bool IsBinaryValue { get { return this.Tag == Tags.BinaryValue; } }
public BinaryPV AsBinaryValue { get { return ((BinaryValueWrapper)this).Item; } }
public static PropertyStates NewBinaryValue(BinaryPV binaryValue)
{
return new BinaryValueWrapper(binaryValue);
}
public bool IsEventType { get { return this.Tag == Tags.EventType; } }
public EventType AsEventType { get { return ((EventTypeWrapper)this).Item; } }
public static PropertyStates NewEventType(EventType eventType)
{
return new EventTypeWrapper(eventType);
}
public bool IsPolarity { get { return this.Tag == Tags.Polarity; } }
public Polarity AsPolarity { get { return ((PolarityWrapper)this).Item; } }
public static PropertyStates NewPolarity(Polarity polarity)
{
return new PolarityWrapper(polarity);
}
public bool IsProgramChange { get { return this.Tag == Tags.ProgramChange; } }
public ProgramRequest AsProgramChange { get { return ((ProgramChangeWrapper)this).Item; } }
public static PropertyStates NewProgramChange(ProgramRequest programChange)
{
return new ProgramChangeWrapper(programChange);
}
public bool IsProgramState { get { return this.Tag == Tags.ProgramState; } }
public ProgramState AsProgramState { get { return ((ProgramStateWrapper)this).Item; } }
public static PropertyStates NewProgramState(ProgramState programState)
{
return new ProgramStateWrapper(programState);
}
public bool IsReasonForHalt { get { return this.Tag == Tags.ReasonForHalt; } }
public ProgramError AsReasonForHalt { get { return ((ReasonForHaltWrapper)this).Item; } }
public static PropertyStates NewReasonForHalt(ProgramError reasonForHalt)
{
return new ReasonForHaltWrapper(reasonForHalt);
}
public bool IsReliability { get { return this.Tag == Tags.Reliability; } }
public Reliability AsReliability { get { return ((ReliabilityWrapper)this).Item; } }
public static PropertyStates NewReliability(Reliability reliability)
{
return new ReliabilityWrapper(reliability);
}
public bool IsState { get { return this.Tag == Tags.State; } }
public EventState AsState { get { return ((StateWrapper)this).Item; } }
public static PropertyStates NewState(EventState state)
{
return new StateWrapper(state);
}
public bool IsSystemStatus { get { return this.Tag == Tags.SystemStatus; } }
public DeviceStatus AsSystemStatus { get { return ((SystemStatusWrapper)this).Item; } }
public static PropertyStates NewSystemStatus(DeviceStatus systemStatus)
{
return new SystemStatusWrapper(systemStatus);
}
public bool IsUnits { get { return this.Tag == Tags.Units; } }
public EngineeringUnits AsUnits { get { return ((UnitsWrapper)this).Item; } }
public static PropertyStates NewUnits(EngineeringUnits units)
{
return new UnitsWrapper(units);
}
public bool IsUnsignedValue { get { return this.Tag == Tags.UnsignedValue; } }
public uint AsUnsignedValue { get { return ((UnsignedValueWrapper)this).Item; } }
public static PropertyStates NewUnsignedValue(uint unsignedValue)
{
return new UnsignedValueWrapper(unsignedValue);
}
public bool IsLifeSafetyMode { get { return this.Tag == Tags.LifeSafetyMode; } }
public LifeSafetyMode AsLifeSafetyMode { get { return ((LifeSafetyModeWrapper)this).Item; } }
public static PropertyStates NewLifeSafetyMode(LifeSafetyMode lifeSafetyMode)
{
return new LifeSafetyModeWrapper(lifeSafetyMode);
}
public bool IsLifeSafetyState { get { return this.Tag == Tags.LifeSafetyState; } }
public LifeSafetyState AsLifeSafetyState { get { return ((LifeSafetyStateWrapper)this).Item; } }
public static PropertyStates NewLifeSafetyState(LifeSafetyState lifeSafetyState)
{
return new LifeSafetyStateWrapper(lifeSafetyState);
}
public static readonly ISchema Schema = new ChoiceSchema(false,
new FieldSchema("BooleanValue", 0, Value<bool>.Schema),
new FieldSchema("BinaryValue", 1, Value<BinaryPV>.Schema),
new FieldSchema("EventType", 2, Value<EventType>.Schema),
new FieldSchema("Polarity", 3, Value<Polarity>.Schema),
new FieldSchema("ProgramChange", 4, Value<ProgramRequest>.Schema),
new FieldSchema("ProgramState", 5, Value<ProgramState>.Schema),
new FieldSchema("ReasonForHalt", 6, Value<ProgramError>.Schema),
new FieldSchema("Reliability", 7, Value<Reliability>.Schema),
new FieldSchema("State", 8, Value<EventState>.Schema),
new FieldSchema("SystemStatus", 9, Value<DeviceStatus>.Schema),
new FieldSchema("Units", 10, Value<EngineeringUnits>.Schema),
new FieldSchema("UnsignedValue", 11, Value<uint>.Schema),
new FieldSchema("LifeSafetyMode", 12, Value<LifeSafetyMode>.Schema),
new FieldSchema("LifeSafetyState", 13, Value<LifeSafetyState>.Schema));
public static PropertyStates Load(IValueStream stream)
{
PropertyStates ret = null;
Tags tag = (Tags)stream.EnterChoice();
switch(tag)
{
case Tags.BooleanValue:
ret = Value<BooleanValueWrapper>.Load(stream);
break;
case Tags.BinaryValue:
ret = Value<BinaryValueWrapper>.Load(stream);
break;
case Tags.EventType:
ret = Value<EventTypeWrapper>.Load(stream);
break;
case Tags.Polarity:
ret = Value<PolarityWrapper>.Load(stream);
break;
case Tags.ProgramChange:
ret = Value<ProgramChangeWrapper>.Load(stream);
break;
case Tags.ProgramState:
ret = Value<ProgramStateWrapper>.Load(stream);
break;
case Tags.ReasonForHalt:
ret = Value<ReasonForHaltWrapper>.Load(stream);
break;
case Tags.Reliability:
ret = Value<ReliabilityWrapper>.Load(stream);
break;
case Tags.State:
ret = Value<StateWrapper>.Load(stream);
break;
case Tags.SystemStatus:
ret = Value<SystemStatusWrapper>.Load(stream);
break;
case Tags.Units:
ret = Value<UnitsWrapper>.Load(stream);
break;
case Tags.UnsignedValue:
ret = Value<UnsignedValueWrapper>.Load(stream);
break;
case Tags.LifeSafetyMode:
ret = Value<LifeSafetyModeWrapper>.Load(stream);
break;
case Tags.LifeSafetyState:
ret = Value<LifeSafetyStateWrapper>.Load(stream);
break;
default:
throw new Exception();
}
stream.LeaveChoice();
return ret;
}
public static void Save(IValueSink sink, PropertyStates value)
{
sink.EnterChoice((byte)value.Tag);
switch(value.Tag)
{
case Tags.BooleanValue:
Value<BooleanValueWrapper>.Save(sink, (BooleanValueWrapper)value);
break;
case Tags.BinaryValue:
Value<BinaryValueWrapper>.Save(sink, (BinaryValueWrapper)value);
break;
case Tags.EventType:
Value<EventTypeWrapper>.Save(sink, (EventTypeWrapper)value);
break;
case Tags.Polarity:
Value<PolarityWrapper>.Save(sink, (PolarityWrapper)value);
break;
case Tags.ProgramChange:
Value<ProgramChangeWrapper>.Save(sink, (ProgramChangeWrapper)value);
break;
case Tags.ProgramState:
Value<ProgramStateWrapper>.Save(sink, (ProgramStateWrapper)value);
break;
case Tags.ReasonForHalt:
Value<ReasonForHaltWrapper>.Save(sink, (ReasonForHaltWrapper)value);
break;
case Tags.Reliability:
Value<ReliabilityWrapper>.Save(sink, (ReliabilityWrapper)value);
break;
case Tags.State:
Value<StateWrapper>.Save(sink, (StateWrapper)value);
break;
case Tags.SystemStatus:
Value<SystemStatusWrapper>.Save(sink, (SystemStatusWrapper)value);
break;
case Tags.Units:
Value<UnitsWrapper>.Save(sink, (UnitsWrapper)value);
break;
case Tags.UnsignedValue:
Value<UnsignedValueWrapper>.Save(sink, (UnsignedValueWrapper)value);
break;
case Tags.LifeSafetyMode:
Value<LifeSafetyModeWrapper>.Save(sink, (LifeSafetyModeWrapper)value);
break;
case Tags.LifeSafetyState:
Value<LifeSafetyStateWrapper>.Save(sink, (LifeSafetyStateWrapper)value);
break;
default:
throw new Exception();
}
sink.LeaveChoice();
}
public enum Tags : byte
{
BooleanValue = 0,
BinaryValue = 1,
EventType = 2,
Polarity = 3,
ProgramChange = 4,
ProgramState = 5,
ReasonForHalt = 6,
Reliability = 7,
State = 8,
SystemStatus = 9,
Units = 10,
UnsignedValue = 11,
LifeSafetyMode = 12,
LifeSafetyState = 13
}
public partial class BooleanValueWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.BooleanValue; } }
public bool Item { get; private set; }
public BooleanValueWrapper(bool item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<bool>.Schema;
public static new BooleanValueWrapper Load(IValueStream stream)
{
var temp = Value<bool>.Load(stream);
return new BooleanValueWrapper(temp);
}
public static void Save(IValueSink sink, BooleanValueWrapper value)
{
Value<bool>.Save(sink, value.Item);
}
}
public partial class BinaryValueWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.BinaryValue; } }
public BinaryPV Item { get; private set; }
public BinaryValueWrapper(BinaryPV item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<BinaryPV>.Schema;
public static new BinaryValueWrapper Load(IValueStream stream)
{
var temp = Value<BinaryPV>.Load(stream);
return new BinaryValueWrapper(temp);
}
public static void Save(IValueSink sink, BinaryValueWrapper value)
{
Value<BinaryPV>.Save(sink, value.Item);
}
}
public partial class EventTypeWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.EventType; } }
public EventType Item { get; private set; }
public EventTypeWrapper(EventType item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<EventType>.Schema;
public static new EventTypeWrapper Load(IValueStream stream)
{
var temp = Value<EventType>.Load(stream);
return new EventTypeWrapper(temp);
}
public static void Save(IValueSink sink, EventTypeWrapper value)
{
Value<EventType>.Save(sink, value.Item);
}
}
public partial class PolarityWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.Polarity; } }
public Polarity Item { get; private set; }
public PolarityWrapper(Polarity item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<Polarity>.Schema;
public static new PolarityWrapper Load(IValueStream stream)
{
var temp = Value<Polarity>.Load(stream);
return new PolarityWrapper(temp);
}
public static void Save(IValueSink sink, PolarityWrapper value)
{
Value<Polarity>.Save(sink, value.Item);
}
}
public partial class ProgramChangeWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.ProgramChange; } }
public ProgramRequest Item { get; private set; }
public ProgramChangeWrapper(ProgramRequest item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ProgramRequest>.Schema;
public static new ProgramChangeWrapper Load(IValueStream stream)
{
var temp = Value<ProgramRequest>.Load(stream);
return new ProgramChangeWrapper(temp);
}
public static void Save(IValueSink sink, ProgramChangeWrapper value)
{
Value<ProgramRequest>.Save(sink, value.Item);
}
}
public partial class ProgramStateWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.ProgramState; } }
public ProgramState Item { get; private set; }
public ProgramStateWrapper(ProgramState item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ProgramState>.Schema;
public static new ProgramStateWrapper Load(IValueStream stream)
{
var temp = Value<ProgramState>.Load(stream);
return new ProgramStateWrapper(temp);
}
public static void Save(IValueSink sink, ProgramStateWrapper value)
{
Value<ProgramState>.Save(sink, value.Item);
}
}
public partial class ReasonForHaltWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.ReasonForHalt; } }
public ProgramError Item { get; private set; }
public ReasonForHaltWrapper(ProgramError item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ProgramError>.Schema;
public static new ReasonForHaltWrapper Load(IValueStream stream)
{
var temp = Value<ProgramError>.Load(stream);
return new ReasonForHaltWrapper(temp);
}
public static void Save(IValueSink sink, ReasonForHaltWrapper value)
{
Value<ProgramError>.Save(sink, value.Item);
}
}
public partial class ReliabilityWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.Reliability; } }
public Reliability Item { get; private set; }
public ReliabilityWrapper(Reliability item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<Reliability>.Schema;
public static new ReliabilityWrapper Load(IValueStream stream)
{
var temp = Value<Reliability>.Load(stream);
return new ReliabilityWrapper(temp);
}
public static void Save(IValueSink sink, ReliabilityWrapper value)
{
Value<Reliability>.Save(sink, value.Item);
}
}
public partial class StateWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.State; } }
public EventState Item { get; private set; }
public StateWrapper(EventState item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<EventState>.Schema;
public static new StateWrapper Load(IValueStream stream)
{
var temp = Value<EventState>.Load(stream);
return new StateWrapper(temp);
}
public static void Save(IValueSink sink, StateWrapper value)
{
Value<EventState>.Save(sink, value.Item);
}
}
public partial class SystemStatusWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.SystemStatus; } }
public DeviceStatus Item { get; private set; }
public SystemStatusWrapper(DeviceStatus item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<DeviceStatus>.Schema;
public static new SystemStatusWrapper Load(IValueStream stream)
{
var temp = Value<DeviceStatus>.Load(stream);
return new SystemStatusWrapper(temp);
}
public static void Save(IValueSink sink, SystemStatusWrapper value)
{
Value<DeviceStatus>.Save(sink, value.Item);
}
}
public partial class UnitsWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.Units; } }
public EngineeringUnits Item { get; private set; }
public UnitsWrapper(EngineeringUnits item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<EngineeringUnits>.Schema;
public static new UnitsWrapper Load(IValueStream stream)
{
var temp = Value<EngineeringUnits>.Load(stream);
return new UnitsWrapper(temp);
}
public static void Save(IValueSink sink, UnitsWrapper value)
{
Value<EngineeringUnits>.Save(sink, value.Item);
}
}
public partial class UnsignedValueWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.UnsignedValue; } }
public uint Item { get; private set; }
public UnsignedValueWrapper(uint item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<uint>.Schema;
public static new UnsignedValueWrapper Load(IValueStream stream)
{
var temp = Value<uint>.Load(stream);
return new UnsignedValueWrapper(temp);
}
public static void Save(IValueSink sink, UnsignedValueWrapper value)
{
Value<uint>.Save(sink, value.Item);
}
}
public partial class LifeSafetyModeWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.LifeSafetyMode; } }
public LifeSafetyMode Item { get; private set; }
public LifeSafetyModeWrapper(LifeSafetyMode item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<LifeSafetyMode>.Schema;
public static new LifeSafetyModeWrapper Load(IValueStream stream)
{
var temp = Value<LifeSafetyMode>.Load(stream);
return new LifeSafetyModeWrapper(temp);
}
public static void Save(IValueSink sink, LifeSafetyModeWrapper value)
{
Value<LifeSafetyMode>.Save(sink, value.Item);
}
}
public partial class LifeSafetyStateWrapper : PropertyStates
{
public override Tags Tag { get { return Tags.LifeSafetyState; } }
public LifeSafetyState Item { get; private set; }
public LifeSafetyStateWrapper(LifeSafetyState item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<LifeSafetyState>.Schema;
public static new LifeSafetyStateWrapper Load(IValueStream stream)
{
var temp = Value<LifeSafetyState>.Load(stream);
return new LifeSafetyStateWrapper(temp);
}
public static void Save(IValueSink sink, LifeSafetyStateWrapper value)
{
Value<LifeSafetyState>.Save(sink, value.Item);
}
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct DocumentHandleCollection : IReadOnlyCollection<DocumentHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal DocumentHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.DocumentTable.NumberOfRows;
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<DocumentHandle> IEnumerable<DocumentHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<DocumentHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public DocumentHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return DocumentHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodDebugInformationHandleCollection : IReadOnlyCollection<MethodDebugInformationHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodDebugInformationHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.MethodDebugInformationTable.NumberOfRows;
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<MethodDebugInformationHandle> IEnumerable<MethodDebugInformationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodDebugInformationHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public MethodDebugInformationHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return MethodDebugInformationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct LocalScopeHandleCollection : IReadOnlyCollection<LocalScopeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal LocalScopeHandleCollection(MetadataReader reader, int methodDefinitionRowId)
{
Debug.Assert(reader != null);
_reader = reader;
if (methodDefinitionRowId == 0)
{
_firstRowId = 1;
_lastRowId = reader.LocalScopeTable.NumberOfRows;
}
else
{
reader.LocalScopeTable.GetLocalScopeRange(methodDefinitionRowId, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<LocalScopeHandle> IEnumerable<LocalScopeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<LocalScopeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public LocalScopeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return LocalScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
public struct ChildrenEnumerator : IEnumerator<LocalScopeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _parentEndOffset;
private readonly int _parentRowId;
private readonly MethodDefinitionHandle _parentMethodRowId;
// parent rid: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal ChildrenEnumerator(MetadataReader reader, int parentRowId)
{
_reader = reader;
_parentEndOffset = reader.LocalScopeTable.GetEndOffset(parentRowId);
_parentMethodRowId = reader.LocalScopeTable.GetMethod(parentRowId);
_currentRowId = 0;
_parentRowId = parentRowId;
}
public LocalScopeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return LocalScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
int currentRowId = _currentRowId;
if (currentRowId == EnumEnded)
{
return false;
}
int currentEndOffset;
int nextRowId;
if (currentRowId == 0)
{
currentEndOffset = -1;
nextRowId = _parentRowId + 1;
}
else
{
currentEndOffset = _reader.LocalScopeTable.GetEndOffset(currentRowId);
nextRowId = currentRowId + 1;
}
int rowCount = _reader.LocalScopeTable.NumberOfRows;
while (true)
{
if (nextRowId > rowCount ||
_parentMethodRowId != _reader.LocalScopeTable.GetMethod(nextRowId))
{
_currentRowId = EnumEnded;
return false;
}
int nextEndOffset = _reader.LocalScopeTable.GetEndOffset(nextRowId);
// If the end of the next scope is lesser than or equal the current end
// then it's nested into the current scope and thus not a child of
// the current scope parent.
if (nextEndOffset > currentEndOffset)
{
// If the end of the next scope is greater than the parent end,
// then we ran out of the children.
if (nextEndOffset > _parentEndOffset)
{
_currentRowId = EnumEnded;
return false;
}
_currentRowId = nextRowId;
return true;
}
nextRowId++;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct LocalVariableHandleCollection : IReadOnlyCollection<LocalVariableHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal LocalVariableHandleCollection(MetadataReader reader, LocalScopeHandle scope)
{
Debug.Assert(reader != null);
_reader = reader;
if (scope.IsNil)
{
_firstRowId = 1;
_lastRowId = reader.LocalVariableTable.NumberOfRows;
}
else
{
reader.GetLocalVariableRange(scope, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<LocalVariableHandle> IEnumerable<LocalVariableHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<LocalVariableHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public LocalVariableHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return LocalVariableHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct LocalConstantHandleCollection : IReadOnlyCollection<LocalConstantHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal LocalConstantHandleCollection(MetadataReader reader, LocalScopeHandle scope)
{
Debug.Assert(reader != null);
_reader = reader;
if (scope.IsNil)
{
_firstRowId = 1;
_lastRowId = reader.LocalConstantTable.NumberOfRows;
}
else
{
reader.GetLocalConstantRange(scope, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<LocalConstantHandle> IEnumerable<LocalConstantHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<LocalConstantHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public LocalConstantHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return LocalConstantHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct ImportScopeCollection : IReadOnlyCollection<ImportScopeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal ImportScopeCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.ImportScopeTable.NumberOfRows;
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<ImportScopeHandle> IEnumerable<ImportScopeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ImportScopeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public ImportScopeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return ImportScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct CustomDebugInformationHandleCollection : IReadOnlyCollection<CustomDebugInformationHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal CustomDebugInformationHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.CustomDebugInformationTable.NumberOfRows;
}
internal CustomDebugInformationHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
Debug.Assert(!handle.IsNil);
_reader = reader;
reader.CustomDebugInformationTable.GetRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<CustomDebugInformationHandle> IEnumerable<CustomDebugInformationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<CustomDebugInformationHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public CustomDebugInformationHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return CustomDebugInformationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: DebuggerAttributes
**
**
** Purpose: Attributes for debugger
**
**
===========================================================*/
namespace System.Diagnostics {
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerStepperBoundaryAttribute : Attribute
{
public DebuggerStepperBoundaryAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor |AttributeTargets.Struct, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute () {}
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module, AllowMultiple = false)]
[ComVisible(true)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
[ComVisible(true)]
public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
DisableOptimizations = 0x100,
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_debuggingModes = 0;
if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
}
public DebuggableAttribute(DebuggingModes modes)
{
m_debuggingModes = modes;
}
public bool IsJITTrackingEnabled
{
get { return ((m_debuggingModes & DebuggingModes.Default) != 0); }
}
public bool IsJITOptimizerDisabled
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
}
}
// DebuggerBrowsableState states are defined as follows:
// Never never show this element
// Expanded expansion of the class is done, so that all visible internal members are shown
// Collapsed expansion of the class is not performed. Internal visible members are hidden
// RootHidden The target element itself should not be shown, but should instead be
// automatically expanded to have its members displayed.
// Default value is collapsed
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
[ComVisible(true)]
public enum DebuggerBrowsableState
{
Never = 0,
//Expanded is not supported in this release
//Expanded = 1,
Collapsed = 2,
RootHidden = 3
}
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
[ComVisible(true)]
public sealed class DebuggerBrowsableAttribute: Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if( state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException("state");
Contract.EndContractBlock();
this.state = state;
}
public DebuggerBrowsableState State
{
get { return state; }
}
}
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerTypeProxyAttribute: Attribute
{
private string typeName;
private string targetName;
private Type target;
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null) {
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
this.typeName = type.AssemblyQualifiedName;
}
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
}
public string ProxyTypeName
{
get { return typeName; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
// This string can include text between { and } which can be either a field,
// property or method (as will be documented in mscorlib). In the C# case,
// a general expression will be allowed which only has implicit access to the this pointer
// for the current instance of the target type. The expression will be limited,
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
private string value;
private string type;
private string targetName;
private Type target;
public DebuggerDisplayAttribute(string value)
{
if( value == null ) {
this.value = "";
}
else {
this.value = value;
}
name = "";
type = "";
}
public string Value
{
get { return this.value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
/// <summary>
/// Signifies that the attributed type has a visualizer which is pointed
/// to by the parameter type name strings.
/// </summary>
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerVisualizerAttribute: Attribute
{
private string visualizerObjectSourceName;
private string visualizerName;
private string description;
private string targetName;
private Type target;
public DebuggerVisualizerAttribute(string visualizerTypeName)
{
this.visualizerName = visualizerTypeName;
}
public DebuggerVisualizerAttribute(string visualizerTypeName, string visualizerObjectSourceTypeName)
{
this.visualizerName = visualizerTypeName;
this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
}
public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource)
{
if (visualizerObjectSource == null) {
throw new ArgumentNullException("visualizerObjectSource");
}
Contract.EndContractBlock();
this.visualizerName = visualizerTypeName;
this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer)
{
if (visualizer == null) {
throw new ArgumentNullException("visualizer");
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource)
{
if (visualizer == null) {
throw new ArgumentNullException("visualizer");
}
if (visualizerObjectSource == null) {
throw new ArgumentNullException("visualizerObjectSource");
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName)
{
if (visualizer == null) {
throw new ArgumentNullException("visualizer");
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
}
public string VisualizerObjectSourceTypeName
{
get { return visualizerObjectSourceName; }
}
public string VisualizerTypeName
{
get { return visualizerName; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
set { targetName = value; }
get { return targetName; }
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System.ComponentModel.Composition;
#endregion
using System;
using System.IO;
using System.Globalization;
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40)
using System.Threading.Tasks;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Text;
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) && !PORTABLE40
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
public static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings> DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#if !NET20
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#endif
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#endif
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
return text;
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
return (!nullable) ? "0.0" : Null;
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text = null;
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
text = value.ToString("D", CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
#endif
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
return Null;
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter)
{
if (delimiter != '"' && delimiter != '\'')
throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value);
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string) value);
case PrimitiveTypeCode.Char:
return ToString((char) value);
case PrimitiveTypeCode.Boolean:
return ToString((bool) value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte) value);
case PrimitiveTypeCode.Int16:
return ToString((short) value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort) value);
case PrimitiveTypeCode.Int32:
return ToString((int) value);
case PrimitiveTypeCode.Byte:
return ToString((byte) value);
case PrimitiveTypeCode.UInt32:
return ToString((uint) value);
case PrimitiveTypeCode.Int64:
return ToString((long) value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong) value);
case PrimitiveTypeCode.Single:
return ToString((float) value);
case PrimitiveTypeCode.Double:
return ToString((double) value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime) value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal) value);
#if !(NETFX_CORE || PORTABLE)
case PrimitiveTypeCode.DBNull:
return Null;
#endif
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset) value);
#endif
case PrimitiveTypeCode.Guid:
return ToString((Guid) value);
case PrimitiveTypeCode.Uri:
return ToString((Uri) value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan) value);
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, Formatting.None, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
/// Specifing the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40)
/// <summary>
/// Asynchronously serializes the specified object to a JSON string.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value)
{
return SerializeObjectAsync(value, Formatting.None, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using formatting.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
{
return SerializeObjectAsync(value, formatting, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
}
#endif
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T) DeserializeObject(value, typeof (T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T) DeserializeObject(value, typeof (T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, "value");
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
jsonSerializer.CheckAdditionalContent = true;
return jsonSerializer.Deserialize(new JsonTextReader(sr), type);
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40)
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// Deserialization will happen on a new thread.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value)
{
return DeserializeObjectAsync<T>(value, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// Deserialization will happen on a new thread.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// Deserialization will happen on a new thread.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value)
{
return DeserializeObjectAsync(value, null, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// Deserialization will happen on a new thread.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
}
#endif
#endregion
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40)
/// <summary>
/// Asynchronously populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous populate operation.
/// </returns>
public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
}
#endif
#if !(SILVERLIGHT || PORTABLE40 || PORTABLE || NETFX_CORE)
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the XML node to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the XML node to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>
/// and writes a .NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XmlDocument) DeserializeObject(value, typeof (XmlDocument), converter);
}
#endif
#if !NET20 && (!(SILVERLIGHT) || WINDOWS_PHONE) && !PORTABLE40
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>
/// and writes a .NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XDocument) DeserializeObject(value, typeof (XDocument), converter);
}
#endif
}
}
| |
// (c) Copyright Esri, 2010 - 2016
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using System.Xml;
using ESRI.ArcGIS.OSM.OSMClassExtension;
using System.Globalization;
using ESRI.ArcGIS.DataSourcesFile;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("3379c124-ea23-49f7-905a-03c3694a6fdb")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPExport2OSM")]
public class OSMGPExport2OSM : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
int in_featureDatasetParameterNumber, out_osmFileLocationParameterNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
OSMUtility _osmUtility = null;
ISpatialReference m_wgs84 = null;
public OSMGPExport2OSM()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
_osmUtility = new OSMUtility();
ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_Export2OSMName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));
// get the name of the feature dataset
int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");
string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
System.Xml.XmlWriter xmlWriter = null;
try
{
xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
}
catch (Exception ex)
{
message.AddError(120021, ex.Message);
return;
}
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("osm"); // start the osm root node
xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute
xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute
// write all the nodes
// use a feature search cursor to loop through all the known points and write them out as osm node
IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;
if (osmFeatureClasses == null)
{
message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
return;
}
IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");
if (osmPointFeatureClass == null)
{
message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
return;
}
// check the extension of the point feature class to determine its version
int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();
IFeatureCursor searchCursor = null;
System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
int pointCounter = 0;
string nodesExportedMessage = String.Empty;
// collect the indices for the point feature class once
int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID");
int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion");
int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid");
int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser");
int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible");
int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags");
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmPointFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));
IFeature currentFeature = searchCursor.NextFeature();
IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == true)
{
// convert the found point feature into a osm node representation to store into the OSM XML file
node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);
pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);
// increase the point counter to later status report
pointCounter++;
currentFeature = searchCursor.NextFeature();
}
else
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loader so far
nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
message.AddMessage(nodesExportedMessage);
return;
}
}
}
nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
message.AddMessage(nodesExportedMessage);
// next loop through the line and polygon feature classes to export those features as ways
// in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");
if (osmLineFeatureClass == null)
{
message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
return;
}
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg"));
// as we are looping through the line and polygon feature classes let's collect the multi-part features separately
// as they are considered relations in the OSM world
List<relation> multiPartElements = new List<relation>();
System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
int lineCounter = 0;
int relationCounter = 0;
string waysExportedMessage = String.Empty;
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmLineFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
IFeature currentFeature = searchCursor.NextFeature();
// collect the indices for the point feature class once
int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID");
int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion");
int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid");
int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser");
int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible");
int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags");
int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers");
IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
return;
}
//test if the feature geometry has multiple parts
IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;
if (geometryCollection != null)
{
if (geometryCollection.GeometryCount == 1)
{
// convert the found polyline feature into a osm way representation to store into the OSM XML file
way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);
// increase the line counter for later status report
lineCounter++;
}
else
{
relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
multiPartElements.Add(osmRelation);
// increase the line counter for later status report
relationCounter++;
}
}
currentFeature = searchCursor.NextFeature();
}
}
IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;
if (osmPolygonFeatureClass == null)
{
message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
return;
}
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmPolygonFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
IFeature currentFeature = searchCursor.NextFeature();
// collect the indices for the point feature class once
int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID");
int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion");
int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid");
int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser");
int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible");
int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags");
int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers");
IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
return;
}
//test if the feature geometry has multiple parts
IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;
if (geometryCollection != null)
{
if (geometryCollection.GeometryCount == 1)
{
// convert the found polyline feature into a osm way representation to store into the OSM XML file
way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);
// increase the line counter for later status report
lineCounter++;
}
else
{
relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
multiPartElements.Add(osmRelation);
// increase the line counter for later status report
relationCounter++;
}
}
currentFeature = searchCursor.NextFeature();
}
}
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
// now let's go through the relation table
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");
if (relationTable == null)
{
message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
return;
}
System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
string relationsExportedMessage = String.Empty;
using (ComReleaser comReleaser = new ComReleaser())
{
ICursor rowCursor = relationTable.Search(null, false);
comReleaser.ManageLifetime(rowCursor);
IRow currentRow = rowCursor.NextRow();
// collect the indices for the relation table once
int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID");
int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion");
int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid");
int relationUserFieldIndex = relationTable.Fields.FindField("osmuser");
int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible");
int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags");
int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers");
IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;
while (currentRow != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
return;
}
relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);
// increase the line counter for later status report
relationCounter++;
currentRow = rowCursor.NextRow();
}
}
// lastly let's serialize the collected multipart-geometries back into relation elements
foreach (relation currentRelation in multiPartElements)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
return;
}
relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
relationCounter++;
}
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
}
catch (Exception ex)
{
message.AddError(11111, ex.StackTrace);
message.AddError(120026, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_Export2OSMName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return String.Empty;
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpexport2osm.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_Export2OSMName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
//
IArray parameterArray = new ArrayClass();
// input feature dataset (required)
IGPParameterEdit3 inputOSMDataset = new GPParameterClass() as IGPParameterEdit3;
inputOSMDataset.DataType = new DEFeatureDatasetTypeClass();
inputOSMDataset.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputOSMDataset.DisplayName = resourceManager.GetString("GPTools_OSMGPExport2OSM_desc_inputDataset_desc");
inputOSMDataset.Name = "in_osmFeatureDataset";
inputOSMDataset.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_featureDatasetParameterNumber = 0;
parameterArray.Add(inputOSMDataset);
// output osm XML file
IGPParameterEdit3 outputOSMFile = new GPParameterClass() as IGPParameterEdit3;
outputOSMFile.DataType = new DEFileTypeClass();
outputOSMFile.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputOSMFile.DisplayName = resourceManager.GetString("GPTools_OSMGPExport2OSM_desc_outputXMLFile_desc");
outputOSMFile.Name = "out_osmXMLFile";
outputOSMFile.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFileDomain osmFileDomainFilter = new GPFileDomainClass();
osmFileDomainFilter.AddType("osm");
outputOSMFile.Domain = osmFileDomainFilter as IGPDomain;
out_osmFileLocationParameterNumber = 1;
parameterArray.Add(outputOSMFile);
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(in_featureDatasetParameterNumber));
// get the name of the feature dataset
int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");
if (fdDemlimiterPosition == -1)
{
Messages.ReplaceError(in_featureDatasetParameterNumber, -33, resourceManager.GetString("GPTools_OSMGPExport2OSM_invalid_featuredataset"));
}
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
private String ConvertPointFeatureToXmlString(IFeature currentFeature, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion)
{
StringBuilder xmlNodeStringBuilder = new StringBuilder(200);
if (currentFeature == null)
throw new ArgumentNullException("currentFeature");
object featureValue = DBNull.Value;
string latitudeString = String.Empty;
string longitudeString = String.Empty;
if (currentFeature.Shape.IsEmpty == false)
{
IPoint wgs84Point = currentFeature.Shape as IPoint;
wgs84Point.Project(m_wgs84);
NumberFormatInfo exportCultureInfo = new CultureInfo("en-US", false).NumberFormat;
exportCultureInfo.NumberDecimalDigits = 6;
latitudeString = wgs84Point.Y.ToString("N", exportCultureInfo);
longitudeString = wgs84Point.X.ToString("N", exportCultureInfo);
Marshal.ReleaseComObject(wgs84Point);
}
string osmIDString = String.Empty;
if (osmIDFieldIndex != -1)
{
osmIDString = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex));
}
string changeSetString = String.Empty;
if (changesetIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
changeSetString = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex));
}
}
string osmVersionString = String.Empty;
if (osmVersionFieldIndex != -1)
{
featureValue = currentFeature.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmVersionString = Convert.ToString(featureValue);
}
}
string userIDString = String.Empty;
if (userIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
userIDString = Convert.ToString(featureValue);
}
}
string userNameString = String.Empty;
if (userNameFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
userNameString = Convert.ToString(featureValue);
}
}
string timeStampString = String.Empty;
if (timeStampFieldIndex != -1)
{
featureValue = currentFeature.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
timeStampString = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
string visibilityString = bool.TrueString;
if (visibleFieldIndex != -1)
{
featureValue = currentFeature.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
try
{
visibilityString = Convert.ToString(featureValue);
}
catch { }
}
}
tag[] tags = null;
if (tagsFieldIndex > -1)
{
tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace);
}
// no tags only the node itself
if (tags != null || tags.Length > 0)
{
xmlNodeStringBuilder.Append("<node id=\"");
xmlNodeStringBuilder.Append(osmIDString);
xmlNodeStringBuilder.Append("\" version=\"");
xmlNodeStringBuilder.Append(osmVersionString);
xmlNodeStringBuilder.Append("\" timestamp=\"");
xmlNodeStringBuilder.Append(timeStampString);
xmlNodeStringBuilder.Append("\" uid=\"");
xmlNodeStringBuilder.Append(userIDString);
xmlNodeStringBuilder.Append("\" user=\"");
xmlNodeStringBuilder.Append(userNameString);
xmlNodeStringBuilder.Append("\" changeset=\"");
xmlNodeStringBuilder.Append(changeSetString);
xmlNodeStringBuilder.Append("\" lat=\"");
xmlNodeStringBuilder.Append(latitudeString);
xmlNodeStringBuilder.Append("\" lon=\"");
xmlNodeStringBuilder.Append(longitudeString);
xmlNodeStringBuilder.AppendLine("\" />");
}
else
{
xmlNodeStringBuilder.Append("<node id=\"");
xmlNodeStringBuilder.Append(osmIDString);
xmlNodeStringBuilder.Append("\" version=\"");
xmlNodeStringBuilder.Append(osmVersionString);
xmlNodeStringBuilder.Append("\" timestamp=\"");
xmlNodeStringBuilder.Append(timeStampString);
xmlNodeStringBuilder.Append("\" uid=\"");
xmlNodeStringBuilder.Append(userIDString);
xmlNodeStringBuilder.Append("\" user=\"");
xmlNodeStringBuilder.Append(userNameString);
xmlNodeStringBuilder.Append("\" changeset=\"");
xmlNodeStringBuilder.Append(changeSetString);
xmlNodeStringBuilder.Append("\" lat=\"");
xmlNodeStringBuilder.Append(latitudeString);
xmlNodeStringBuilder.Append("\" lon=\"");
xmlNodeStringBuilder.Append(longitudeString);
xmlNodeStringBuilder.AppendLine("\" >");
foreach (tag item in tags)
{
xmlNodeStringBuilder.Append("<tag k=\"");
xmlNodeStringBuilder.Append(item.k);
xmlNodeStringBuilder.Append("\" v=\"");
xmlNodeStringBuilder.Append(item.v);
xmlNodeStringBuilder.AppendLine("\" />");
}
xmlNodeStringBuilder.AppendLine("</node>");
}
return xmlNodeStringBuilder.ToString();
}
private node ConvertPointFeatureToOSMNode(IFeature currentFeature, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion)
{
if (currentFeature == null)
throw new ArgumentNullException("currentFeature");
node osmNode = new node();
object featureValue = DBNull.Value;
if (currentFeature.Shape.IsEmpty == false)
{
IPoint wgs84Point = currentFeature.Shape as IPoint;
wgs84Point.Project(m_wgs84);
NumberFormatInfo exportCultureInfo = new CultureInfo("en-US", false).NumberFormat;
exportCultureInfo.NumberDecimalDigits = 6;
osmNode.lat = wgs84Point.Y.ToString("N", exportCultureInfo);
osmNode.lon = wgs84Point.X.ToString("N", exportCultureInfo);
Marshal.ReleaseComObject(wgs84Point);
}
if (osmIDFieldIndex != -1)
{
osmNode.id = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.changeset = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentFeature.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentFeature.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentFeature.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
try
{
osmNode.visible = (nodeVisible)Enum.Parse(typeof(nodeVisible), Convert.ToString(featureValue));
}
catch
{
osmNode.visible = nodeVisible.@true;
}
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace);
if (tags.Length != 0)
{
osmNode.tag = tags;
}
}
return osmNode;
}
private way ConvertFeatureToOSMWay(IFeature currentFeature, IWorkspace featureWorkspace, IFeatureClass pointFeatureClass, int osmIDPointFieldIndex, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion)
{
if (currentFeature == null)
throw new ArgumentNullException("currentFeature");
way osmWay = new way();
object featureValue = DBNull.Value;
List<nd> vertexIDs = new List<nd>();
if (currentFeature.Shape.IsEmpty == false)
{
IPointCollection pointCollection = currentFeature.Shape as IPointCollection;
if (currentFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
{
for (int pointIndex = 0; pointIndex < pointCollection.PointCount - 1; pointIndex++)
{
nd vertex = new nd();
vertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(pointIndex));
vertexIDs.Add(vertex);
}
// the last node is the first one again even though it doesn't have an internal ID
nd lastVertex = new nd();
lastVertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(0));
vertexIDs.Add(lastVertex);
}
else
{
for (int pointIndex = 0; pointIndex < pointCollection.PointCount; pointIndex++)
{
nd vertex = new nd();
vertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(pointIndex));
vertexIDs.Add(vertex);
}
}
osmWay.nd = vertexIDs.ToArray();
}
if (osmIDFieldIndex != -1)
{
osmWay.id = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.changeset = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentFeature.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentFeature.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentFeature.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
try
{
osmWay.visible = (wayVisible)Enum.Parse(typeof(wayVisible), Convert.ToString(featureValue));
}
catch
{
osmWay.visible = wayVisible.@true;
}
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace);
if (tags.Length != 0)
{
osmWay.tag = tags;
}
}
return osmWay;
}
private relation ConvertRowToOSMRelation(IRow currentRow, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int membersFieldIndex, int extensionVersion)
{
if (currentRow == null)
throw new ArgumentNullException("currentRow");
relation osmRelation = new relation();
object featureValue = DBNull.Value;
List<object> relationItems = new List<object>();
if (membersFieldIndex != -1)
{
member[] members = _osmUtility.retrieveMembers(currentRow, membersFieldIndex);
relationItems.AddRange(members);
}
if (osmIDFieldIndex != -1)
{
osmRelation.id = Convert.ToString(currentRow.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentRow.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.changeset = Convert.ToString(currentRow.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentRow.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentRow.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentRow.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentRow.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentRow.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.visible = Convert.ToString(featureValue);
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentRow, tagsFieldIndex, featureWorkspace);
//// if the row is of type IFeature and a polygon then add the type=multipolygon tag
//if (currentRow is IFeature)
//{
// IFeature currentFeature = currentRow as IFeature;
// if (currentFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
// {
// tag mpTag = new tag();
// mpTag.k = "type";
// mpTag.v = "multipolygon";
// relationItems.Add(mpTag);
// }
//}
if (tags.Length != 0)
{
relationItems.AddRange(tags);
}
}
// add all items (member and tags) to the relation element
osmRelation.Items = relationItems.ToArray();
return osmRelation;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using Android.Content;
using Android.Graphics;
using Android.Views;
using Android.Widget;
using com.refractored.fab;
using CorporateBsGenerator;
using CorporateBsGenerator.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using ListView = Xamarin.Forms.ListView;
using Path = System.IO.Path;
[assembly: ExportRenderer(typeof(FloatingActionButtonView), typeof(FloatingActionButtonViewRenderer))]
namespace CorporateBsGenerator.Droid
{
public class FloatingActionButtonViewRenderer : ViewRenderer<FloatingActionButtonView, FrameLayout>
{
private const int MARGIN_DIPS = 16;
private const int FAB_HEIGHT_NORMAL = 56;
private const int FAB_HEIGHT_MINI = 40;
private const int FAB_FRAME_HEIGHT_WITH_PADDING = MARGIN_DIPS * 2 + FAB_HEIGHT_NORMAL;
private const int FAB_FRAME_WIDTH_WITH_PADDING = MARGIN_DIPS * 2 + FAB_HEIGHT_NORMAL;
private const int FAB_MINI_FRAME_HEIGHT_WITH_PADDING = MARGIN_DIPS * 2 + FAB_HEIGHT_MINI;
private const int FAB_MINI_FRAME_WIDTH_WITH_PADDING = MARGIN_DIPS * 2 + FAB_HEIGHT_MINI;
private readonly Context context;
private readonly FloatingActionButton fab;
private int appearingListItemIndex;
public FloatingActionButtonViewRenderer()
{
this.context = Forms.Context;
var d = this.context.Resources.DisplayMetrics.Density;
var margin = (int) (MARGIN_DIPS * d); // margin in pixels
this.fab = new FloatingActionButton(this.context);
var lp = new FrameLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
lp.Gravity = GravityFlags.CenterVertical | GravityFlags.CenterHorizontal;
lp.LeftMargin = margin;
lp.TopMargin = margin;
lp.BottomMargin = margin;
lp.RightMargin = margin;
this.fab.LayoutParameters = lp;
}
public void Hide(bool animate = true)
{
this.fab.Hide(animate);
}
public void Show(bool animate = true)
{
this.fab.Show(animate);
}
protected override void OnElementChanged(ElementChangedEventArgs<FloatingActionButtonView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= HandlePropertyChanged;
// Experimental - proper hiding and showing of the FAB is dependent on the objects in the list being unique.
if (e.OldElement.ParentList != null)
{
e.OldElement.ParentList.ItemAppearing -= OnListItemAppearing;
e.OldElement.ParentList.ItemDisappearing -= OnListItemDisappearing;
}
}
if (Element != null)
{
Element.PropertyChanged += HandlePropertyChanged;
// Experimental - proper hiding and showing of the FAB is dependent on the objects in the list being unique.
if (Element.ParentList != null)
{
Element.ParentList.ItemAppearing += OnListItemAppearing;
Element.ParentList.ItemDisappearing += OnListItemDisappearing;
}
}
Element.Show = Show;
Element.Hide = Hide;
SetFabImage(Element.ImageName);
SetFabSize(Element.Size);
this.fab.ColorNormal = Element.ColorNormal.ToAndroid();
this.fab.ColorPressed = Element.ColorPressed.ToAndroid();
this.fab.ColorRipple = Element.ColorRipple.ToAndroid();
this.fab.HasShadow = Element.HasShadow;
this.fab.Click += Fab_Click;
var frame = new FrameLayout(this.context);
frame.RemoveAllViews();
frame.AddView(this.fab);
SetNativeControl(frame);
}
private void Fab_Click(object sender, EventArgs e)
{
Action<object, EventArgs> clicked = Element.Clicked;
if (Element != null)
{
clicked?.Invoke(sender, e);
if (Element.Command != null && Element.Command.CanExecute(null)) Element.Command.Execute(null);
}
}
private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Content")
{
Tracker.UpdateLayout();
}
else if (e.PropertyName == FloatingActionButtonView.ColorNormalProperty.PropertyName)
{
this.fab.ColorNormal = Element.ColorNormal.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ColorPressedProperty.PropertyName)
{
this.fab.ColorPressed = Element.ColorPressed.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ColorRippleProperty.PropertyName)
{
this.fab.ColorRipple = Element.ColorRipple.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ImageNameProperty.PropertyName)
{
SetFabImage(Element.ImageName);
}
else if (e.PropertyName == FloatingActionButtonView.SizeProperty.PropertyName)
{
SetFabSize(Element.Size);
}
else if (e.PropertyName == FloatingActionButtonView.HasShadowProperty.PropertyName)
{
this.fab.HasShadow = Element.HasShadow;
}
}
private void OnListItemAppearing(object sender, ItemVisibilityEventArgs e)
{
// Experimental - proper hiding and showing of the FAB is dependent on the objects in the list being unique.
var list = sender as ListView;
var items = list?.ItemsSource as IList;
if (items != null)
{
var index = items.IndexOf(e.Item);
if (index < this.appearingListItemIndex)
{
this.appearingListItemIndex = index;
this.fab.Show();
}
else
{
this.appearingListItemIndex = index;
}
}
}
private void OnListItemDisappearing(object sender, ItemVisibilityEventArgs e)
{
// Experimental - proper hiding and showing of the FAB is dependent on the objects in the list being unique.
var list = sender as ListView;
var items = list?.ItemsSource as IList;
if (items != null)
{
var index = items.IndexOf(e.Item);
if (index < this.appearingListItemIndex && index != 0)
{
this.appearingListItemIndex = index;
this.fab.Hide();
}
else
{
this.appearingListItemIndex = index;
}
}
}
private void SetFabImage(string imageName)
{
if (!string.IsNullOrWhiteSpace(imageName))
{
try
{
var drawableNameWithoutExtension = Path.GetFileNameWithoutExtension(imageName);
var resources = this.context.Resources;
var imageResourceName = resources.GetIdentifier(drawableNameWithoutExtension, "drawable", this.context.PackageName);
this.fab.SetImageBitmap(BitmapFactory.DecodeResource(this.context.Resources, imageResourceName));
}
catch (Exception ex)
{
throw new FileNotFoundException("There was no Android Drawable by that name.", ex);
}
}
}
private void SetFabSize(FloatingActionButtonSize size)
{
if (size == FloatingActionButtonSize.Mini)
{
this.fab.Size = FabSize.Mini;
Element.WidthRequest = FAB_MINI_FRAME_WIDTH_WITH_PADDING;
Element.HeightRequest = FAB_MINI_FRAME_HEIGHT_WITH_PADDING;
}
else
{
this.fab.Size = FabSize.Normal;
Element.WidthRequest = FAB_FRAME_WIDTH_WITH_PADDING;
Element.HeightRequest = FAB_FRAME_HEIGHT_WITH_PADDING;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime.Synchronization
{
using System;
using System.Runtime.CompilerServices;
public sealed class CriticalSection : WaitableObject
{
public static class Configuration
{
public static bool ImmediatelyTransferOwnership
{
[ConfigurationOption("CriticalSection__ImmediatelyTransferOwnership")]
get
{
return false;
}
}
public static bool AvoidPriorityInversionOnRelease
{
[ConfigurationOption("CriticalSection__AvoidPriorityInversionOnRelease")]
get
{
return false;
}
}
}
//
// State
//
volatile ThreadImpl m_ownerThread;
volatile int m_nestingCount;
//
// Constructor Methods
//
public CriticalSection()
{
}
//
// Helper Methods
//
public override bool Acquire( SchedulerTime timeout )
{
ThreadImpl thisThread = ThreadImpl.CurrentThread;
if(thisThread == null)
{
//
// Special case for boot code path: all locks are transparent.
//
return true;
}
//
// Fast shortcut for non-contended case.
//
if(m_ownerThread == null)
{
#pragma warning disable 420
if(System.Threading.Interlocked.CompareExchange< ThreadImpl >( ref m_ownerThread, thisThread, null ) == null)
#pragma warning restore 420
{
thisThread.AcquiredWaitableObject( this );
return true;
}
}
//
// Fast shortcut for nested calls.
//
if(m_ownerThread == thisThread)
{
m_nestingCount++;
return true;
}
using(Synchronization.WaitingRecord.Holder holder = WaitingRecord.Holder.Get( thisThread, this, timeout ))
{
while(true)
{
bool fNotify = false;
bool fResult = false;
using(SmartHandles.InterruptState.Disable())
{
if(holder.ShouldTryToAcquire)
{
if(m_ownerThread == null)
{
m_ownerThread = thisThread;
fNotify = true;
fResult = true;
}
else
{
if(m_ownerThread == thisThread)
{
m_nestingCount++;
fResult = true;
}
}
}
}
if(fNotify)
{
thisThread.AcquiredWaitableObject( this );
}
if(fResult)
{
return fResult;
}
if(holder.RequestProcessed)
{
return holder.RequestFulfilled;
}
}
}
}
public override void Release()
{
ThreadImpl thisThread = ThreadImpl.CurrentThread;
if(thisThread == null)
{
//
// Special case for boot code path: all locks are transparent.
//
return;
}
if(m_ownerThread != thisThread)
{
#if EXCEPTION_STRINGS
throw new Exception( "Releasing waitable object not owned by thread" );
#else
throw new Exception();
#endif
}
if(m_nestingCount > 0)
{
m_nestingCount--;
return;
}
thisThread.ReleasedWaitableObject( this );
ThreadImpl ownerThread = null;
ThreadImpl wakeupThread = null;
using(SmartHandles.InterruptState.Disable())
{
WaitingRecord wr = m_listWaiting.FirstTarget();
if(wr != null)
{
wakeupThread = wr.Source;
if( Configuration.ImmediatelyTransferOwnership ||
(Configuration.AvoidPriorityInversionOnRelease && thisThread.Priority < wakeupThread.Priority) )
{
ownerThread = wakeupThread;
wr.RequestFulfilled = true;
}
}
m_ownerThread = ownerThread;
}
if(ownerThread != null)
{
ownerThread.AcquiredWaitableObject( this );
}
if(wakeupThread != null)
{
wakeupThread.Wakeup();
}
}
//--//
//
// Access Methods
//
}
}
| |
namespace HelixToolkit.Wpf.SharpDX
{
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using global::SharpDX;
using global::SharpDX.Direct3D;
using global::SharpDX.Direct3D11;
using global::SharpDX.DXGI;
using Color = global::SharpDX.Color;
public class LineGeometryModel3D : GeometryModel3D
{
private InputLayout vertexLayout;
private Buffer vertexBuffer;
private Buffer indexBuffer;
private Buffer instanceBuffer;
private EffectTechnique effectTechnique;
private EffectTransformVariables effectTransforms;
private EffectVectorVariable vViewport, vLineParams; // vFrustum,
//private DepthStencilState depthStencilState;
//private LineGeometry3D geometry;
private EffectScalarVariable bHasInstances;
private Matrix[] instanceArray;
private bool hasInstances = false;
private bool isChanged = true;
public Color Color
{
get { return (Color)this.GetValue(ColorProperty); }
set { this.SetValue(ColorProperty, value); }
}
public static readonly DependencyProperty ColorProperty =
DependencyProperty.Register("Color", typeof(Color), typeof(LineGeometryModel3D), new UIPropertyMetadata(Color.Black, (o, e) => ((LineGeometryModel3D)o).OnColorChanged()));
public double Thickness
{
get { return (double)this.GetValue(ThicknessProperty); }
set { this.SetValue(ThicknessProperty, value); }
}
public static readonly DependencyProperty ThicknessProperty =
DependencyProperty.Register("Thickness", typeof(double), typeof(LineGeometryModel3D), new UIPropertyMetadata(1.0));
public double Smoothness
{
get { return (double)this.GetValue(SmoothnessProperty); }
set { this.SetValue(SmoothnessProperty, value); }
}
public static readonly DependencyProperty SmoothnessProperty =
DependencyProperty.Register("Smoothness", typeof(double), typeof(LineGeometryModel3D), new UIPropertyMetadata(0.0));
public IEnumerable<Matrix> Instances
{
get { return (IEnumerable<Matrix>)this.GetValue(InstancesProperty); }
set { this.SetValue(InstancesProperty, value); }
}
public static readonly DependencyProperty InstancesProperty =
DependencyProperty.Register("Instances", typeof(IEnumerable<Matrix>), typeof(LineGeometryModel3D), new UIPropertyMetadata(null, InstancesChanged));
public double HitTestThickness
{
get { return (double)this.GetValue(HitTestThicknessProperty); }
set { this.SetValue(HitTestThicknessProperty, value); }
}
public static readonly DependencyProperty HitTestThicknessProperty =
DependencyProperty.Register("HitTestThickness", typeof(double), typeof(LineGeometryModel3D), new UIPropertyMetadata(1.0));
protected static void InstancesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var model = (LineGeometryModel3D)d;
if (e.NewValue != null)
{
model.instanceArray = ((IEnumerable<Matrix>)e.NewValue).ToArray();
}
else
{
model.instanceArray = null;
}
model.isChanged = true;
}
public override bool HitTest(Ray rayWS, ref List<HitTestResult> hits)
{
LineGeometry3D lineGeometry3D;
Viewport3DX viewport;
if (this.Visibility == Visibility.Collapsed ||
this.IsHitTestVisible == false ||
(viewport = FindVisualAncestor<Viewport3DX>(this.renderHost as DependencyObject)) == null ||
(lineGeometry3D = this.Geometry as LineGeometry3D) == null)
{
return false;
}
// revert unprojection; probably better: overloaded HitTest() for LineGeometryModel3D?
var svpm = viewport.GetScreenViewProjectionMatrix();
var smvpm = this.modelMatrix * svpm;
var clickPoint4 = new Vector4(rayWS.Position + rayWS.Direction, 1);
Vector4.Transform(ref clickPoint4, ref svpm, out clickPoint4);
var clickPoint = clickPoint4.ToVector3();
var result = new HitTestResult { IsValid = false, Distance = double.MaxValue };
var maxDist = this.HitTestThickness;
var lastDist = double.MaxValue;
var index = 0;
foreach (var line in lineGeometry3D.Lines)
{
var p0 = Vector3.TransformCoordinate(line.P0, smvpm);
var p1 = Vector3.TransformCoordinate(line.P1, smvpm);
Vector3 hitPoint;
float t;
var dist = LineBuilder.GetPointToLineDistance2D(ref clickPoint, ref p0, ref p1, out hitPoint, out t);
if (dist < lastDist && dist <= maxDist)
{
lastDist = dist;
Vector4 res;
var lp0 = line.P0;
Vector3.Transform(ref lp0, ref this.modelMatrix, out res);
lp0 = res.ToVector3();
var lp1 = line.P1;
Vector3.Transform(ref lp1, ref this.modelMatrix, out res);
lp1 = res.ToVector3();
var lv = lp1 - lp0;
var hitPointWS = lp0 + lv * t;
result.Distance = (rayWS.Position - hitPointWS).Length();
result.PointHit = hitPointWS.ToPoint3D();
result.ModelHit = this;
result.IsValid = true;
result.Tag = index; // ToDo: LineHitTag with additional info
}
index++;
}
if (result.IsValid)
{
hits.Add(result);
}
return result.IsValid;
}
protected override void OnRasterStateChanged(int depthBias)
{
if (this.IsAttached)
{
Disposer.RemoveAndDispose(ref this.rasterState);
/// --- set up rasterizer states
var rasterStateDesc = new RasterizerStateDescription()
{
FillMode = FillMode.Solid,
CullMode = CullMode.None,
DepthBias = depthBias,
DepthBiasClamp = -1000,
SlopeScaledDepthBias = -2,
IsDepthClipEnabled = true,
IsFrontCounterClockwise = false,
IsMultisampleEnabled = true,
//IsAntialiasedLineEnabled = true, // Intel HD 3000 doesn't like this (#10051) and it's not needed
//IsScissorEnabled = true,
};
try { this.rasterState = new RasterizerState(this.Device, rasterStateDesc); }
catch (System.Exception)
{
}
}
}
private void OnColorChanged()
{
if (this.IsAttached)
{
/// --- set up buffers
this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, LinesVertex.SizeInBytes, this.CreateLinesVertexArray());
}
}
/// <summary>
///
/// </summary>
/// <param name="host"></param>
public override void Attach(IRenderHost host)
{
/// --- attach
this.renderTechnique = Techniques.RenderLines;
base.Attach(host);
if (this.Geometry == null)
return;
#if DEFERRED
if (renderHost.RenderTechnique == Techniques.RenderDeferred || renderHost.RenderTechnique == Techniques.RenderGBuffer)
return;
#endif
// --- get device
this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique);
this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name);
this.effectTransforms = new EffectTransformVariables(this.effect);
// --- get geometry
var geometry = this.Geometry as LineGeometry3D;
// -- set geometry if given
if (geometry != null)
{
/// --- set up buffers
this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, LinesVertex.SizeInBytes, this.CreateLinesVertexArray());
/// --- set up indexbuffer
this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array);
}
/// --- init instances buffer
this.hasInstances = (this.Instances != null)&&(this.Instances.Any());
this.bHasInstances = this.effect.GetVariableByName("bHasInstances").AsScalar();
if (this.hasInstances)
{
this.instanceBuffer = Buffer.Create(this.Device, this.instanceArray, new BufferDescription(Matrix.SizeInBytes * this.instanceArray.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0));
}
/// --- set up const variables
this.vViewport = effect.GetVariableByName("vViewport").AsVector();
//this.vFrustum = effect.GetVariableByName("vFrustum").AsVector();
this.vLineParams = effect.GetVariableByName("vLineParams").AsVector();
/// --- set effect per object const vars
var lineParams = new Vector4((float)this.Thickness, (float)this.Smoothness, 0, 0);
this.vLineParams.Set(lineParams);
/// === debug hack
//{
// var texDiffuseMapView = ShaderResourceView.FromFile(device, @"G:\Projects\Deformation Project\FrameworkWPF2012\Externals\HelixToolkit-SharpDX\Source\Examples\SharpDX.Wpf\LightingDemo\TextureCheckerboard2.jpg");
// var texDiffuseMap = effect.GetVariableByName("texDiffuseMap").AsShaderResource();
// texDiffuseMap.SetResource(texDiffuseMapView);
//}
/// --- create raster state
this.OnRasterStateChanged(this.DepthBias);
//this.rasterState = new RasterizerState(this.device, rasterStateDesc);
/// --- set up depth stencil state
//var depthStencilDesc = new DepthStencilStateDescription()
//{
// DepthComparison = Comparison.Less,
// DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All,
// IsDepthEnabled = true,
//};
//this.depthStencilState = new DepthStencilState(this.device, depthStencilDesc);
/// --- flush
this.Device.ImmediateContext.Flush();
}
/// <summary>
///
/// </summary>
public override void Detach()
{
Disposer.RemoveAndDispose(ref this.vertexBuffer);
Disposer.RemoveAndDispose(ref this.indexBuffer);
Disposer.RemoveAndDispose(ref this.instanceBuffer);
//Disposer.RemoveAndDispose(ref this.vFrustum);
Disposer.RemoveAndDispose(ref this.vViewport);
Disposer.RemoveAndDispose(ref this.vLineParams);
Disposer.RemoveAndDispose(ref this.rasterState);
//Disposer.RemoveAndDispose(ref this.depthStencilState);
Disposer.RemoveAndDispose(ref this.bHasInstances);
this.renderTechnique = null;
this.effectTechnique = null;
this.vertexLayout = null;
base.Detach();
}
/// <summary>
///
/// </summary>
public override void Render(RenderContext renderContext)
{
/// --- do not render, if not enabled
if (!this.IsRendering)
return;
if (this.Geometry == null)
return;
if (this.Visibility != System.Windows.Visibility.Visible)
return;
#if DEFERRED
if (renderHost.RenderTechnique == Techniques.RenderDeferred || renderHost.RenderTechnique == Techniques.RenderGBuffer)
return;
#endif
if (renderContext.IsShadowPass)
if (!this.IsThrowingShadow)
return;
/// --- since these values are changed only per window resize, we set them only once here
//if (this.isResized || renderContext.Camera != this.lastCamera)
{
//this.isResized = false;
//this.lastCamera = renderContext.Camera;
if (renderContext.Camera is ProjectionCamera)
{
var c = renderContext.Camera as ProjectionCamera;
// viewport: W,H,0,0
var viewport = new Vector4((float)renderContext.Canvas.ActualWidth, (float)renderContext.Canvas.ActualHeight, 0, 0);
var ar = viewport.X / viewport.Y;
this.vViewport.Set(ref viewport);
// Actually, we don't really need vFrustum because we already know the depth of the projected line.
//var fov = 100.0; // this is a fake value, since the line shader does not use it!
//var zn = c.NearPlaneDistance > 0 ? c.NearPlaneDistance : 0.1;
//var zf = c.FarPlaneDistance + 0.0;
// frustum: FOV,AR,N,F
//var frustum = new Vector4((float)fov, (float)ar, (float)zn, (float)zf);
//this.vFrustum.Set(ref frustum);
}
}
/// --- set transform paramerers
var worldMatrix = this.modelMatrix * renderContext.worldMatrix;
this.effectTransforms.mWorld.SetMatrix(ref worldMatrix);
/// --- set effect per object const vars
var lineParams = new Vector4((float)this.Thickness, (float)this.Smoothness, 0, 0);
this.vLineParams.Set(lineParams);
/// --- set context
this.Device.ImmediateContext.InputAssembler.InputLayout = this.vertexLayout;
this.Device.ImmediateContext.InputAssembler.SetIndexBuffer(this.indexBuffer, Format.R32_UInt, 0);
this.Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;
/// --- check instancing
this.hasInstances = (this.Instances != null)&&(this.Instances.Any());
this.bHasInstances.Set(this.hasInstances);
/// --- set rasterstate
this.Device.ImmediateContext.Rasterizer.State = this.rasterState;
if (this.hasInstances)
{
/// --- update instance buffer
if (this.isChanged)
{
this.instanceBuffer = Buffer.Create(this.Device, this.instanceArray, new BufferDescription(Matrix.SizeInBytes * this.instanceArray.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0));
DataStream stream;
Device.ImmediateContext.MapSubresource(this.instanceBuffer, MapMode.WriteDiscard, global::SharpDX.Direct3D11.MapFlags.None, out stream);
stream.Position = 0;
stream.WriteRange(this.instanceArray, 0, this.instanceArray.Length);
Device.ImmediateContext.UnmapSubresource(this.instanceBuffer, 0);
stream.Dispose();
this.isChanged = false;
}
/// --- INSTANCING: need to set 2 buffers
this.Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new[]
{
new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0),
new VertexBufferBinding(this.instanceBuffer, Matrix.SizeInBytes, 0),
});
/// --- render the geometry
for (int i = 0; i < this.effectTechnique.Description.PassCount; i++)
{
this.effectTechnique.GetPassByIndex(i).Apply(Device.ImmediateContext);
this.Device.ImmediateContext.DrawIndexedInstanced(this.Geometry.Indices.Count, this.instanceArray.Length, 0, 0, 0);
}
}
else
{
/// --- bind buffer
this.Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0));
/// --- render the geometry
this.effectTechnique.GetPassByIndex(0).Apply(this.Device.ImmediateContext);
this.Device.ImmediateContext.DrawIndexed(this.Geometry.Indices.Count, 0, 0);
}
}
/// <summary>
///
/// </summary>
public override void Dispose()
{
this.Detach();
}
/// <summary>
/// Creates a <see cref="T:LinesVertex[]"/>.
/// </summary>
private LinesVertex[] CreateLinesVertexArray()
{
var positions = this.Geometry.Positions.Array;
var vertexCount = positions.Length;
var color = this.Color;
var result = new LinesVertex[vertexCount];
for (var i = 0; i < vertexCount; i++)
{
result[i] = new LinesVertex
{
Position = new Vector4(positions[i], 1f),
Color = color,
};
}
return result;
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableArrayExtensionsTest
{
private static readonly ImmutableArray<int> s_emptyDefault = default(ImmutableArray<int>);
private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>();
private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1);
private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3);
private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1));
private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null);
private static readonly ImmutableArray<int>.Builder s_emptyBuilder = ImmutableArray.Create<int>().ToBuilder();
private static readonly ImmutableArray<int>.Builder s_oneElementBuilder = ImmutableArray.Create<int>(1).ToBuilder();
private static readonly ImmutableArray<int>.Builder s_manyElementsBuilder = ImmutableArray.Create<int>(1, 2, 3).ToBuilder();
[Fact]
public void Select()
{
Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(s_manyElements, n => n + 3));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(s_manyElements, null));
}
[Fact]
public void SelectEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select<int, bool>(s_emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select(s_emptyDefault, n => true));
}
[Fact]
public void SelectEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(s_empty, null));
Assert.False(ImmutableArrayExtensions.Select(s_empty, n => true).Any());
}
[Fact]
public void SelectMany()
{
Func<int, IEnumerable<int>> collectionSelector = i => Enumerable.Range(i, 10);
Func<int, int, int> resultSelector = (i, e) => e * 2;
foreach (var arr in new[] { s_empty, s_oneElement, s_manyElements })
{
Assert.Equal(
Enumerable.SelectMany(arr, collectionSelector, resultSelector),
ImmutableArrayExtensions.SelectMany(arr, collectionSelector, resultSelector));
}
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_emptyDefault, null, null));
Assert.Throws<ArgumentNullException>(() =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, null, (i, e) => e));
Assert.Throws<ArgumentNullException>(() =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, i => new[] { i }, null));
}
[Fact]
public void Where()
{
Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(s_manyElements, n => n > 1));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(s_manyElements, null));
}
[Fact]
public void WhereEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, n => true));
}
[Fact]
public void WhereEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(s_empty, null));
Assert.False(ImmutableArrayExtensions.Where(s_empty, n => true).Any());
}
[Fact]
public void Any()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(s_oneElement, null));
Assert.True(ImmutableArrayExtensions.Any(s_oneElement));
Assert.True(ImmutableArrayExtensions.Any(s_manyElements, n => n == 2));
Assert.False(ImmutableArrayExtensions.Any(s_manyElements, n => n == 4));
Assert.True(ImmutableArrayExtensions.Any(s_oneElementBuilder));
}
[Fact]
public void AnyEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, null));
}
[Fact]
public void AnyEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(s_empty, null));
Assert.False(ImmutableArrayExtensions.Any(s_empty));
Assert.False(ImmutableArrayExtensions.Any(s_empty, n => true));
}
[Fact]
public void All()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(s_oneElement, null));
Assert.False(ImmutableArrayExtensions.All(s_manyElements, n => n == 2));
Assert.True(ImmutableArrayExtensions.All(s_manyElements, n => n > 0));
}
[Fact]
public void AllEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, null));
}
[Fact]
public void AllEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(s_empty, null));
Assert.True(ImmutableArrayExtensions.All(s_empty, n => { Assert.True(false); return false; })); // predicate should never be invoked.
}
[Fact]
public void SequenceEqual()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, (IEnumerable<int>)null));
foreach (IEqualityComparer<int> comparer in new[] { null, EqualityComparer<int>.Default })
{
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.ToArray(), comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_oneElement.ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_oneElement.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.Add(1).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), (IEnumerable<int>)s_manyElements.Add(2).ToArray(), comparer));
}
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, (a, b) => true));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2), (a, b) => a == b));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(1), (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), (a, b) => false));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_oneElement, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_empty));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_empty, (IEnumerable<int>)null));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty.ToArray()));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => true));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => false));
}
[Fact]
public void Aggregate()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(s_oneElement, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(s_oneElement, 1, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, null, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, (a, b) => a + b, null));
Assert.Equal(Enumerable.Aggregate(s_manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a));
}
[Fact]
public void AggregateEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, 1, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_emptyDefault, 1, (a, b) => a + b, a => a));
}
[Fact]
public void AggregateEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.Aggregate(s_empty, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate(s_empty, 1, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(s_empty, 1, (a, b) => a + b, a => a));
}
[Fact]
public void ElementAt()
{
// Basis for some assertions that follow
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_manyElements, -1));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(s_emptyDefault, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_manyElements, -1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAt(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAt(s_manyElements, 2));
}
[Fact]
public void ElementAtOrDefault()
{
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, -1));
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 3));
Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 2));
}
[Fact]
public void First()
{
Assert.Equal(Enumerable.First(s_oneElement), ImmutableArrayExtensions.First(s_oneElement));
Assert.Equal(Enumerable.First(s_oneElement, i => true), ImmutableArrayExtensions.First(s_oneElement, i => true));
Assert.Equal(Enumerable.First(s_manyElements), ImmutableArrayExtensions.First(s_manyElements));
Assert.Equal(Enumerable.First(s_manyElements, i => true), ImmutableArrayExtensions.First(s_manyElements, i => true));
Assert.Equal(Enumerable.First(s_oneElementBuilder), ImmutableArrayExtensions.First(s_oneElementBuilder));
Assert.Equal(Enumerable.First(s_manyElementsBuilder), ImmutableArrayExtensions.First(s_manyElementsBuilder));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_manyElements, i => false));
}
[Fact]
public void FirstEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_emptyBuilder));
}
[Fact]
public void FirstEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(s_emptyDefault, null));
}
[Fact]
public void FirstOrDefault()
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement), ImmutableArrayExtensions.FirstOrDefault(s_oneElement));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements), ImmutableArrayExtensions.FirstOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.FirstOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.FirstOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.FirstOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.FirstOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.FirstOrDefault(s_manyElementsBuilder));
}
[Fact]
public void FirstOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_emptyBuilder));
}
[Fact]
public void FirstOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, null));
}
[Fact]
public void Last()
{
Assert.Equal(Enumerable.Last(s_oneElement), ImmutableArrayExtensions.Last(s_oneElement));
Assert.Equal(Enumerable.Last(s_oneElement, i => true), ImmutableArrayExtensions.Last(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_oneElement, i => false));
Assert.Equal(Enumerable.Last(s_manyElements), ImmutableArrayExtensions.Last(s_manyElements));
Assert.Equal(Enumerable.Last(s_manyElements, i => true), ImmutableArrayExtensions.Last(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_manyElements, i => false));
Assert.Equal(Enumerable.Last(s_oneElementBuilder), ImmutableArrayExtensions.Last(s_oneElementBuilder));
Assert.Equal(Enumerable.Last(s_manyElementsBuilder), ImmutableArrayExtensions.Last(s_manyElementsBuilder));
}
[Fact]
public void LastEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_emptyBuilder));
}
[Fact]
public void LastEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, null));
}
[Fact]
public void LastOrDefault()
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement), ImmutableArrayExtensions.LastOrDefault(s_oneElement));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements), ImmutableArrayExtensions.LastOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.LastOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.LastOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.LastOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.LastOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.LastOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.LastOrDefault(s_manyElementsBuilder));
}
[Fact]
public void LastOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_emptyBuilder));
}
[Fact]
public void LastOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, null));
}
[Fact]
public void Single()
{
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement));
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_oneElement, i => false));
}
[Fact]
public void SingleEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(s_empty, null));
}
[Fact]
public void SingleEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(s_emptyDefault, null));
}
[Fact]
public void SingleOrDefault()
{
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => true));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement, i => false), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements, i => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_oneElement, null));
}
[Fact]
public void SingleOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_empty, null));
}
[Fact]
public void SingleOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, null));
}
[Fact]
public void ToDictionary()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default));
var stringToString = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString(), n => (n * 2).ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal("2", stringToString["1"]);
Assert.Equal("4", stringToString["2"]);
Assert.Equal("6", stringToString["3"]);
var stringToInt = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal(1, stringToInt["1"]);
Assert.Equal(2, stringToInt["2"]);
Assert.Equal(3, stringToInt["3"]);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, EqualityComparer<int>.Default));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n, EqualityComparer<int>.Default));
}
[Fact]
public void ToArray()
{
Assert.Equal(0, ImmutableArrayExtensions.ToArray(s_empty).Length);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(s_emptyDefault));
Assert.Equal(s_manyElements.ToArray(), ImmutableArrayExtensions.ToArray(s_manyElements));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace Inlining
{
public static class ConstantArgsChar
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Chars feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static char Five = (char) 5;
static char Ten = (char) 10;
static char Id(char x)
{
return x;
}
static char F00(char x)
{
return (char) (x * x);
}
static bool Bench00p()
{
char t = (char) 10;
char f = F00(t);
return (f == 100);
}
static bool Bench00n()
{
char t = Ten;
char f = F00(t);
return (f == 100);
}
static bool Bench00p1()
{
char t = Id((char)10);
char f = F00(t);
return (f == 100);
}
static bool Bench00n1()
{
char t = Id(Ten);
char f = F00(t);
return (f == 100);
}
static bool Bench00p2()
{
char t = Id((char)10);
char f = F00(Id(t));
return (f == 100);
}
static bool Bench00n2()
{
char t = Id(Ten);
char f = F00(Id(t));
return (f == 100);
}
static bool Bench00p3()
{
char t = (char) 10;
char f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00n3()
{
char t = Ten;
char f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00p4()
{
char t = (char) 5;
char f = F00((char)(2 * t));
return (f == 100);
}
static bool Bench00n4()
{
char t = Five;
char f = F00((char)(2 * t));
return (f == 100);
}
static char F01(char x)
{
return (char)(1000 / x);
}
static bool Bench01p()
{
char t = (char) 10;
char f = F01(t);
return (f == 100);
}
static bool Bench01n()
{
char t = Ten;
char f = F01(t);
return (f == 100);
}
static char F02(char x)
{
return (char) (20 * (x / 2));
}
static bool Bench02p()
{
char t = (char) 10;
char f = F02(t);
return (f == 100);
}
static bool Bench02n()
{
char t = Ten;
char f = F02(t);
return (f == 100);
}
static char F03(char x)
{
return (char)(91 + 1009 % x);
}
static bool Bench03p()
{
char t = (char) 10;
char f = F03(t);
return (f == 100);
}
static bool Bench03n()
{
char t = Ten;
char f = F03(t);
return (f == 100);
}
static char F04(char x)
{
return (char)(50 * (x % 4));
}
static bool Bench04p()
{
char t = (char) 10;
char f = F04(t);
return (f == 100);
}
static bool Bench04n()
{
char t = Ten;
char f = F04(t);
return (f == 100);
}
static char F05(char x)
{
return (char)((1 << x) - 924);
}
static bool Bench05p()
{
char t = (char) 10;
char f = F05(t);
return (f == 100);
}
static bool Bench05n()
{
char t = Ten;
char f = F05(t);
return (f == 100);
}
static char F051(char x)
{
return (char)(102400 >> x);
}
static bool Bench05p1()
{
char t = (char) 10;
char f = F051(t);
return (f == 100);
}
static bool Bench05n1()
{
char t = Ten;
char f = F051(t);
return (f == 100);
}
static char F06(char x)
{
return (char)(-x + 110);
}
static bool Bench06p()
{
char t = (char) 10;
char f = F06(t);
return (f == 100);
}
static bool Bench06n()
{
char t = Ten;
char f = F06(t);
return (f == 100);
}
static char F07(char x)
{
return (char)(~x + 111);
}
static bool Bench07p()
{
char t = (char) 10;
char f = F07(t);
return (f == 100);
}
static bool Bench07n()
{
char t = Ten;
char f = F07(t);
return (f == 100);
}
static char F071(char x)
{
return (char)((x ^ -1) + 111);
}
static bool Bench07p1()
{
char t = (char) 10;
char f = F071(t);
return (f == 100);
}
static bool Bench07n1()
{
char t = Ten;
char f = F071(t);
return (f == 100);
}
static char F08(char x)
{
return (char)((x & 0x7) + 98);
}
static bool Bench08p()
{
char t = (char) 10;
char f = F08(t);
return (f == 100);
}
static bool Bench08n()
{
char t = Ten;
char f = F08(t);
return (f == 100);
}
static char F09(char x)
{
return (char)((x | 0x7) + 85);
}
static bool Bench09p()
{
char t = (char) 10;
char f = F09(t);
return (f == 100);
}
static bool Bench09n()
{
char t = Ten;
char f = F09(t);
return (f == 100);
}
// Chars feeding comparisons.
//
// Inlining in Bench1xp should enable branch optimization
// Inlining in Bench1xn will not enable branch optimization
static char F10(char x)
{
return x == 10 ? (char) 100 : (char) 0;
}
static bool Bench10p()
{
char t = (char) 10;
char f = F10(t);
return (f == 100);
}
static bool Bench10n()
{
char t = Ten;
char f = F10(t);
return (f == 100);
}
static char F101(char x)
{
return x != 10 ? (char) 0 : (char) 100;
}
static bool Bench10p1()
{
char t = (char) 10;
char f = F101(t);
return (f == 100);
}
static bool Bench10n1()
{
char t = Ten;
char f = F101(t);
return (f == 100);
}
static char F102(char x)
{
return x >= 10 ? (char) 100 : (char) 0;
}
static bool Bench10p2()
{
char t = (char) 10;
char f = F102(t);
return (f == 100);
}
static bool Bench10n2()
{
char t = Ten;
char f = F102(t);
return (f == 100);
}
static char F103(char x)
{
return x <= 10 ? (char) 100 : (char) 0;
}
static bool Bench10p3()
{
char t = (char) 10;
char f = F103(t);
return (f == 100);
}
static bool Bench10n3()
{
char t = Ten;
char f = F102(t);
return (f == 100);
}
static char F11(char x)
{
if (x == 10)
{
return (char) 100;
}
else
{
return (char) 0;
}
}
static bool Bench11p()
{
char t = (char) 10;
char f = F11(t);
return (f == 100);
}
static bool Bench11n()
{
char t = Ten;
char f = F11(t);
return (f == 100);
}
static char F111(char x)
{
if (x != 10)
{
return (char) 0;
}
else
{
return (char) 100;
}
}
static bool Bench11p1()
{
char t = (char) 10;
char f = F111(t);
return (f == 100);
}
static bool Bench11n1()
{
char t = Ten;
char f = F111(t);
return (f == 100);
}
static char F112(char x)
{
if (x > 10)
{
return (char) 0;
}
else
{
return (char) 100;
}
}
static bool Bench11p2()
{
char t = (char) 10;
char f = F112(t);
return (f == 100);
}
static bool Bench11n2()
{
char t = Ten;
char f = F112(t);
return (f == 100);
}
static char F113(char x)
{
if (x < 10)
{
return (char) 0;
}
else
{
return (char) 100;
}
}
static bool Bench11p3()
{
char t = (char) 10;
char f = F113(t);
return (f == 100);
}
static bool Bench11n3()
{
char t = Ten;
char f = F113(t);
return (f == 100);
}
// Ununsed (or effectively unused) parameters
//
// Simple callee analysis may overstate inline benefit
static char F20(char x)
{
return (char) 100;
}
static bool Bench20p()
{
char t = (char) 10;
char f = F20(t);
return (f == 100);
}
static bool Bench20p1()
{
char t = Ten;
char f = F20(t);
return (f == 100);
}
static char F21(char x)
{
return (char)(-x + 100 + x);
}
static bool Bench21p()
{
char t = (char) 10;
char f = F21(t);
return (f == 100);
}
static bool Bench21n()
{
char t = Ten;
char f = F21(t);
return (f == 100);
}
static char F211(char x)
{
return (char)(x - x + 100);
}
static bool Bench21p1()
{
char t = (char) 10;
char f = F211(t);
return (f == 100);
}
static bool Bench21n1()
{
char t = Ten;
char f = F211(t);
return (f == 100);
}
static char F22(char x)
{
if (x > 0)
{
return (char) 100;
}
return (char) 100;
}
static bool Bench22p()
{
char t = (char) 10;
char f = F22(t);
return (f == 100);
}
static bool Bench22p1()
{
char t = Ten;
char f = F22(t);
return (f == 100);
}
static char F23(char x)
{
if (x > 0)
{
return (char)(90 + x);
}
return (char) 100;
}
static bool Bench23p()
{
char t = (char) 10;
char f = F23(t);
return (f == 100);
}
static bool Bench23n()
{
char t = Ten;
char f = F23(t);
return (f == 100);
}
// Multiple parameters
static char F30(char x, char y)
{
return (char)(y * y);
}
static bool Bench30p()
{
char t = (char) 10;
char f = F30(t, t);
return (f == 100);
}
static bool Bench30n()
{
char t = Ten;
char f = F30(t, t);
return (f == 100);
}
static bool Bench30p1()
{
char s = Ten;
char t = (char) 10;
char f = F30(s, t);
return (f == 100);
}
static bool Bench30n1()
{
char s = (char) 10;
char t = Ten;
char f = F30(s, t);
return (f == 100);
}
static bool Bench30p2()
{
char s = (char) 10;
char t = (char) 10;
char f = F30(s, t);
return (f == 100);
}
static bool Bench30n2()
{
char s = Ten;
char t = Ten;
char f = F30(s, t);
return (f == 100);
}
static bool Bench30p3()
{
char s = (char) 10;
char t = s;
char f = F30(s, t);
return (f == 100);
}
static bool Bench30n3()
{
char s = Ten;
char t = s;
char f = F30(s, t);
return (f == 100);
}
static char F31(char x, char y, char z)
{
return (char)(z * z);
}
static bool Bench31p()
{
char t = (char) 10;
char f = F31(t, t, t);
return (f == 100);
}
static bool Bench31n()
{
char t = Ten;
char f = F31(t, t, t);
return (f == 100);
}
static bool Bench31p1()
{
char r = Ten;
char s = Ten;
char t = (char) 10;
char f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n1()
{
char r = (char) 10;
char s = (char) 10;
char t = Ten;
char f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p2()
{
char r = (char) 10;
char s = (char) 10;
char t = (char) 10;
char f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n2()
{
char r = Ten;
char s = Ten;
char t = Ten;
char f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p3()
{
char r = (char) 10;
char s = r;
char t = s;
char f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n3()
{
char r = Ten;
char s = r;
char t = s;
char f = F31(r, s, t);
return (f == 100);
}
// Two args, both used
static char F40(char x, char y)
{
return (char)(x * x + y * y - 100);
}
static bool Bench40p()
{
char t = (char) 10;
char f = F40(t, t);
return (f == 100);
}
static bool Bench40n()
{
char t = Ten;
char f = F40(t, t);
return (f == 100);
}
static bool Bench40p1()
{
char s = Ten;
char t = (char) 10;
char f = F40(s, t);
return (f == 100);
}
static bool Bench40p2()
{
char s = (char) 10;
char t = Ten;
char f = F40(s, t);
return (f == 100);
}
static char F41(char x, char y)
{
return (char)(x * y);
}
static bool Bench41p()
{
char t = (char) 10;
char f = F41(t, t);
return (f == 100);
}
static bool Bench41n()
{
char t = Ten;
char f = F41(t, t);
return (f == 100);
}
static bool Bench41p1()
{
char s = (char) 10;
char t = Ten;
char f = F41(s, t);
return (f == 100);
}
static bool Bench41p2()
{
char s = Ten;
char t = (char) 10;
char f = F41(s, t);
return (f == 100);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench00p1", "Bench00n1",
"Bench00p2", "Bench00n2",
"Bench00p3", "Bench00n3",
"Bench00p4", "Bench00n4",
"Bench01p", "Bench01n",
"Bench02p", "Bench02n",
"Bench03p", "Bench03n",
"Bench04p", "Bench04n",
"Bench05p", "Bench05n",
"Bench05p1", "Bench05n1",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench07p1", "Bench07n1",
"Bench08p", "Bench08n",
"Bench09p", "Bench09n",
"Bench10p", "Bench10n",
"Bench10p1", "Bench10n1",
"Bench10p2", "Bench10n2",
"Bench10p3", "Bench10n3",
"Bench11p", "Bench11n",
"Bench11p1", "Bench11n1",
"Bench11p2", "Bench11n2",
"Bench11p3", "Bench11n3",
"Bench20p", "Bench20p1",
"Bench21p", "Bench21n",
"Bench21p1", "Bench21n1",
"Bench22p", "Bench22p1",
"Bench23p", "Bench23n",
"Bench30p", "Bench30n",
"Bench30p1", "Bench30n1",
"Bench30p2", "Bench30n2",
"Bench30p3", "Bench30n3",
"Bench31p", "Bench31n",
"Bench31p1", "Bench31n1",
"Bench31p2", "Bench31n2",
"Bench31p3", "Bench31n3",
"Bench40p", "Bench40n",
"Bench40p1", "Bench40p2",
"Bench41p", "Bench41n",
"Bench41p1", "Bench41p2"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsChar).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
}
| |
using Orleans;
using System;
using System.Threading.Tasks;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.General
{
/// <summary>
/// Tests that exceptions are correctly propagated.
/// </summary>
public class ExceptionPropagationTests : OrleansTestingBase, IClassFixture<ExceptionPropagationTests.Fixture>
{
private const int TestIterations = 100;
private readonly ITestOutputHelper output;
private readonly Fixture fixture;
private readonly IMessageSerializationGrain exceptionGrain;
private readonly MessageSerializationClientObject clientObject = new MessageSerializationClientObject();
private readonly IMessageSerializationClientObject clientObjectRef;
public ExceptionPropagationTests(ITestOutputHelper output, Fixture fixture)
{
this.output = output;
this.fixture = fixture;
var grainFactory = (IInternalGrainFactory)this.fixture.GrainFactory;
this.exceptionGrain = grainFactory.GetGrain<IMessageSerializationGrain>(GetRandomGrainId());
this.clientObjectRef = grainFactory.CreateObjectReference<IMessageSerializationClientObject>(this.clientObject);
}
public class Fixture : BaseTestClusterFixture
{
}
[Fact, TestCategory("BVT")]
public async Task ExceptionsPropagatedFromGrainToClient()
{
var grain = this.fixture.Client.GetGrain<IExceptionGrain>(0);
var invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(() => grain.ThrowsInvalidOperationException());
Assert.Equal("Test exception", invalidOperationException.Message);
var nullReferenceException = await Assert.ThrowsAsync<NullReferenceException>(() => grain.ThrowsNullReferenceException());
Assert.Equal("null null null", nullReferenceException.Message);
}
[Fact, TestCategory("BVT")]
public async Task BasicExceptionPropagation()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => grain.ThrowsInvalidOperationException());
output.WriteLine(exception.ToString());
Assert.Equal("Test exception", exception.Message);
}
[Fact, TestCategory("BVT")]
public void ExceptionContainsOriginalStackTrace()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
// Explicitly using .Wait() instead of await the task to avoid any modification of the inner exception
var aggEx = Assert.Throws<AggregateException>(
() => grain.ThrowsInvalidOperationException().Wait());
var exception = aggEx.InnerException;
output.WriteLine(exception.ToString());
Assert.IsAssignableFrom<InvalidOperationException>(exception);
Assert.Equal("Test exception", exception.Message);
Assert.Contains("ThrowsInvalidOperationException", exception.StackTrace);
}
[Fact(Skip = "Does not work on .NET Core"), TestCategory("BVT")]
public async Task ExceptionContainsOriginalStackTraceWhenRethrowingLocally()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
try
{
// Use await to force the exception to be rethrown and validate that the remote stack trace is still present
await grain.ThrowsInvalidOperationException();
Assert.True(false, "should have thrown");
}
catch (InvalidOperationException exception)
{
output.WriteLine(exception.ToString());
Assert.IsAssignableFrom<InvalidOperationException>(exception);
Assert.Equal("Test exception", exception.Message);
Assert.Contains("ThrowsInvalidOperationException", exception.StackTrace);
}
}
[Fact, TestCategory("BVT")]
public async Task ExceptionPropagationDoesNotUnwrapAggregateExceptions()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var exception = await Assert.ThrowsAsync<AggregateException>(
() => grain.ThrowsAggregateExceptionWrappingInvalidOperationException());
var nestedEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerException);
Assert.Equal("Test exception", nestedEx.Message);
}
[Fact, TestCategory("BVT")]
public async Task ExceptionPropagationDoesNoFlattenAggregateExceptions()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var exception = await Assert.ThrowsAsync<AggregateException>(
() => grain.ThrowsNestedAggregateExceptionsWrappingInvalidOperationException());
var nestedAggEx = Assert.IsAssignableFrom<AggregateException>(exception.InnerException);
var doubleNestedEx = Assert.IsAssignableFrom<InvalidOperationException>(nestedAggEx.InnerException);
Assert.Equal("Test exception", doubleNestedEx.Message);
}
[Fact, TestCategory("BVT")]
public async Task TaskCancelationPropagation()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
await Assert.ThrowsAsync<TaskCanceledException>(
() => grain.Canceled());
}
[Fact, TestCategory("BVT")]
public async Task GrainForwardingExceptionPropagation()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var otherGrainId = GetRandomGrainId();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => grain.GrainCallToThrowsInvalidOperationException(otherGrainId));
Assert.Equal("Test exception", exception.Message);
}
[Fact, TestCategory("BVT")]
public async Task GrainForwardingExceptionPropagationDoesNotUnwrapAggregateExceptions()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var otherGrainId = GetRandomGrainId();
var exception = await Assert.ThrowsAsync<AggregateException>(
() => grain.GrainCallToThrowsAggregateExceptionWrappingInvalidOperationException(otherGrainId));
var nestedEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerException);
Assert.Equal("Test exception", nestedEx.Message);
}
[Fact, TestCategory("BVT")]
public async Task SynchronousExceptionThrownShouldResultInFaultedTask()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
// start the grain call but don't await it nor wrap in try/catch, to make sure it doesn't throw synchronously
var grainCallTask = grain.ThrowsSynchronousInvalidOperationException();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => grainCallTask);
Assert.Equal("Test exception", exception.Message);
var grainCallTask2 = grain.ThrowsSynchronousInvalidOperationException();
var exception2 = await Assert.ThrowsAsync<InvalidOperationException>(() => grainCallTask2);
Assert.Equal("Test exception", exception2.Message);
}
[Fact(Skip = "Implementation of issue #1378 is still pending"), TestCategory("BVT")]
public void ExceptionPropagationForwardsEntireAggregateException()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
var grainCall = grain.ThrowsMultipleExceptionsAggregatedInFaultedTask();
try
{
// use Wait() so that we get the entire AggregateException ('await' would just catch the first inner exception)
// Do not use Assert.Throws to avoid any tampering of the AggregateException itself from the test framework
grainCall.Wait();
Assert.True(false, "Expected AggregateException");
}
catch (AggregateException exception)
{
output.WriteLine(exception.ToString());
// make sure that all exceptions in the task are present, and not just the first one.
Assert.Equal(2, exception.InnerExceptions.Count);
var firstEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[0]);
Assert.Equal("Test exception 1", firstEx.Message);
var secondEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[1]);
Assert.Equal("Test exception 2", secondEx.Message);
}
}
[Fact, TestCategory("BVT")]
public async Task SynchronousAggregateExceptionThrownShouldResultInFaultedTaskWithOriginalAggregateExceptionUnmodifiedAsInnerException()
{
IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId());
// start the grain call but don't await it nor wrap in try/catch, to make sure it doesn't throw synchronously
var grainCallTask = grain.ThrowsSynchronousAggregateExceptionWithMultipleInnerExceptions();
// assert that the faulted task has an inner exception of type AggregateException, which should be our original exception
var exception = await Assert.ThrowsAsync<AggregateException>(() => grainCallTask);
Assert.StartsWith("Test AggregateException message", exception.Message);
// make sure that all exceptions in the task are present, and not just the first one.
Assert.Equal(2, exception.InnerExceptions.Count);
var firstEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[0]);
Assert.Equal("Test exception 1", firstEx.Message);
var secondEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[1]);
Assert.Equal("Test exception 2", secondEx.Message);
}
/// <summary>
/// Tests that when a client cannot deserialize a request from a grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsClient_Request_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUndeserializableToClient(this.clientObjectRef));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a client cannot serialize a response to a grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsClient_Response_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.GetUnserializableFromClient(this.clientObjectRef));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot deserialize a response from a client, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsClient_Response_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.GetUndeserializableFromClient(this.clientObjectRef));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot serialize a request to a client, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsClient_Request_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUnserializableToClient(this.clientObjectRef));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot deserialize a request from another grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsGrain_Request_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUndeserializableToOtherSilo());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot serialize a request to another grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsGrain_Request_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUnserializableToOtherSilo());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot serialize a response to another grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsGrain_Response_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.GetUnserializableFromOtherSilo());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot deserialize a response from another grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_GrainCallsGrain_Response_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.GetUndeserializableFromOtherSilo());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot deserialize a request from a client, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_ClientCallsGrain_Request_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUndeserializable(new UndeserializableType(32)));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a client cannot serialize a request to a grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_ClientCallsGrain_Request_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => exceptionGrain.SendUnserializable(new UnserializableType()));
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a grain cannot serialize a response to a client, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_ClientCallsGrain_Response_Serialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<Exception>(() => exceptionGrain.GetUnserializable());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
/// <summary>
/// Tests that when a client cannot deserialize a response from a grain, an exception is promptly propagated back to the original caller.
/// </summary>
[Fact, TestCategory("BVT"), TestCategory("Messaging"), TestCategory("Serialization")]
public async Task ExceptionPropagation_ClientCallsGrain_Response_Deserialization_Failure()
{
for (var i = 0; i < TestIterations; i++)
{
var exception = await Assert.ThrowsAnyAsync<Exception>(() => exceptionGrain.GetUndeserializable());
Assert.Contains(UndeserializableType.FailureMessage, exception.Message);
}
}
private class MessageSerializationClientObject : IMessageSerializationClientObject
{
public Task SendUndeserializable(UndeserializableType input) => Task.FromResult(input);
public Task SendUnserializable(UnserializableType input) => Task.FromResult(input);
public Task<UnserializableType> GetUnserializable() => Task.FromResult(new UnserializableType());
public Task<UndeserializableType> GetUndeserializable() => Task.FromResult(new UndeserializableType(35));
}
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
/*
* 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 System.IO;
using System.Reflection;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Framework.Library
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LibraryModule")]
public class LibraryModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_HasRunOnce = false;
private bool m_Enabled = false;
private ILibraryService m_Library;
// private string m_LibraryName = "OpenSim Library";
private Scene m_Scene;
#region ISharedRegionModule
public bool IsSharedModule
{
get { return true; }
}
public string Name
{
get { return "Library Module"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// Store only the first scene
if (m_Scene == null)
{
m_Scene = scene;
}
scene.RegisterModuleInterface<ILibraryService>(m_Library);
}
public void Close()
{
m_Scene = null;
}
public void Initialise(IConfigSource config)
{
m_Enabled = config.Configs["Modules"].GetBoolean("LibraryModule", m_Enabled);
if (m_Enabled)
{
IConfig libConfig = config.Configs["LibraryService"];
if (libConfig != null)
{
string dllName = libConfig.GetString("LocalServiceModule", string.Empty);
m_log.Debug("[LIBRARY MODULE]: Library service dll is " + dllName);
if (dllName != string.Empty)
{
Object[] args = new Object[] { config };
m_Library = ServerUtils.LoadPlugin<ILibraryService>(dllName, args);
}
}
}
if (m_Library == null)
{
m_log.Warn("[LIBRARY MODULE]: No local library service. Module will be disabled.");
m_Enabled = false;
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
// This will never run more than once, even if the region is restarted
if (!m_HasRunOnce)
{
LoadLibrariesFromArchives();
//DumpLibrary();
m_HasRunOnce = true;
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<ILibraryService>(m_Library);
}
#endregion ISharedRegionModule
#region LoadLibraries
private string pathToLibraries = "Library";
protected void LoadLibrariesFromArchives()
{
InventoryFolderImpl lib = m_Library.LibraryRootFolder;
if (lib == null)
{
m_log.Debug("[LIBRARY MODULE]: No library. Ignoring Library Module");
return;
}
RegionInfo regInfo = new RegionInfo();
Scene m_MockScene = new Scene(regInfo);
LocalInventoryService invService = new LocalInventoryService(lib);
m_MockScene.RegisterModuleInterface<IInventoryService>(invService);
m_MockScene.RegisterModuleInterface<IAssetService>(m_Scene.AssetService);
UserAccount uinfo = new UserAccount(lib.Owner);
uinfo.FirstName = "OpenSim";
uinfo.LastName = "Library";
uinfo.ServiceURLs = new Dictionary<string, object>();
foreach (string iarFileName in Directory.GetFiles(pathToLibraries, "*.iar"))
{
string simpleName = Path.GetFileNameWithoutExtension(iarFileName);
m_log.InfoFormat("[LIBRARY MODULE]: Loading library archive {0} ({1})...", iarFileName, simpleName);
simpleName = GetInventoryPathFromName(simpleName);
InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene.InventoryService, m_MockScene.AssetService, m_MockScene.UserAccountService, uinfo, simpleName, iarFileName, false);
try
{
HashSet<InventoryNodeBase> nodes = archread.Execute();
if (nodes != null && nodes.Count == 0)
{
// didn't find the subfolder with the given name; place it on the top
m_log.InfoFormat("[LIBRARY MODULE]: Didn't find {0} in library. Placing archive on the top level", simpleName);
archread.Close();
archread = new InventoryArchiveReadRequest(m_MockScene.InventoryService, m_MockScene.AssetService, m_MockScene.UserAccountService, uinfo, "/", iarFileName, false);
archread.Execute();
}
foreach (InventoryNodeBase node in nodes)
FixPerms(node);
}
catch (Exception e)
{
m_log.DebugFormat("[LIBRARY MODULE]: Exception when processing archive {0}: {1}", iarFileName, e.StackTrace);
}
finally
{
archread.Close();
}
}
}
private void DumpFolder(InventoryFolderImpl folder)
{
foreach (InventoryItemBase item in folder.Items.Values)
{
m_log.DebugFormat(" --> item {0}", item.Name);
}
foreach (InventoryFolderImpl f in folder.RequestListOfFolderImpls())
{
m_log.DebugFormat(" - folder {0}", f.Name);
DumpFolder(f);
}
}
private void FixPerms(InventoryNodeBase node)
{
m_log.DebugFormat("[LIBRARY MODULE]: Fixing perms for {0} {1}", node.Name, node.ID);
if (node is InventoryItemBase)
{
InventoryItemBase item = (InventoryItemBase)node;
item.BasePermissions = (uint)PermissionMask.All;
item.EveryOnePermissions = (uint)PermissionMask.All - (uint)PermissionMask.Modify;
item.CurrentPermissions = (uint)PermissionMask.All;
item.NextPermissions = (uint)PermissionMask.All;
}
}
// private void DumpLibrary()
// {
// InventoryFolderImpl lib = m_Library.LibraryRootFolder;
//
// m_log.DebugFormat(" - folder {0}", lib.Name);
// DumpFolder(lib);
// }
//
// private void DumpLibrary()
// {
// InventoryFolderImpl lib = m_Scene.CommsManager.UserProfileCacheService.LibraryRoot;
//
// m_log.DebugFormat(" - folder {0}", lib.Name);
// DumpFolder(lib);
// }
private string GetInventoryPathFromName(string name)
{
string[] parts = name.Split(new char[] { ' ' });
if (parts.Length == 3)
{
name = string.Empty;
// cut the last part
for (int i = 0; i < parts.Length - 1; i++)
name = name + ' ' + parts[i];
}
return name;
}
#endregion LoadLibraries
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Sdk;
namespace Tests.Collections
{
public abstract class ICollectionTest<T> : IEnumerableTest<T>
{
private readonly bool _expectedIsSynchronized;
protected ICollectionTest(bool isSynchronized)
{
_expectedIsSynchronized = isSynchronized;
ValidArrayTypes = new[] {typeof (object)};
InvalidArrayTypes = new[]
{
typeof (MyInvalidReferenceType),
typeof (MyInvalidValueType)
};
}
protected Type[] ValidArrayTypes { get; set; }
protected Type[] InvalidArrayTypes { get; set; }
protected abstract bool ItemsMustBeUnique { get; }
protected abstract bool ItemsMustBeNonNull { get; }
protected bool ExpectedIsSynchronized
{
get { return _expectedIsSynchronized; }
}
protected virtual bool CopyToOnlySupportsZeroLowerBounds
{
get { return true; }
}
protected ICollection GetCollection(object[] items)
{
IEnumerable obj = GetEnumerable(items);
Assert.IsAssignableFrom<ICollection>(obj);
return (ICollection) obj;
}
[Fact]
public void Count()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
Assert.Equal(items.Length, collection.Count);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = GetCollection(GenerateItems(16));
Assert.Equal(
ExpectedIsSynchronized,
collection.IsSynchronized);
}
[Fact]
public void SyncRootNonNull()
{
ICollection collection = GetCollection(GenerateItems(16));
Assert.NotNull(collection.SyncRoot);
}
[Fact]
public void SyncRootConsistent()
{
ICollection collection = GetCollection(GenerateItems(16));
object syncRoot1 = collection.SyncRoot;
object syncRoot2 = collection.SyncRoot;
Assert.Equal(syncRoot1, syncRoot2);
}
[Fact]
public void SyncRootCanBeLocked()
{
ICollection collection = GetCollection(GenerateItems(16));
lock (collection.SyncRoot)
{
}
}
[Fact]
public void SyncRootUnique()
{
ICollection collection1 = GetCollection(GenerateItems(16));
ICollection collection2 = GetCollection(GenerateItems(16));
Assert.NotEqual(collection1.SyncRoot, collection2.SyncRoot);
}
[Fact]
public void CopyToNull()
{
ICollection collection = GetCollection(GenerateItems(16));
Assert.Throws<ArgumentNullException>(
() => collection.CopyTo(null, 0));
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
[InlineData(int.MaxValue)]
public void CopyToBadIndex(int index)
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
var items2 = (object[]) items.Clone();
Assert.ThrowsAny<ArgumentException>(
() => collection.CopyTo(items2, index));
CollectionAssert.Equal(items, items2);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNonZeroLowerBoundArraySupported))]
public void CopyToArrayWithNonZeroBounds()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
if (CopyToOnlySupportsZeroLowerBounds)
{
Array itemArray = Array.CreateInstance(
typeof (object),
new[] {collection.Count + 8},
new[] {-4});
var tempItemArray = (Array) itemArray.Clone();
Assert.Throws<ArgumentException>(
() => collection.CopyTo(itemArray, 0));
CollectionAssert.Equal(tempItemArray, itemArray);
}
else
{
Array itemArray = Array.CreateInstance(
typeof (object),
new[] {collection.Count + 4},
new[] {-4});
var tempItemArray = (Array) itemArray.Clone();
Assert.Throws<ArgumentException>(
() => collection.CopyTo(itemArray, 1));
CollectionAssert.Equal(tempItemArray, itemArray);
itemArray = Array.CreateInstance(
typeof (object),
new[] {collection.Count + 4},
new[] {-6});
tempItemArray = (Array) itemArray.Clone();
Assert.Throws<ArgumentException>(
() => collection.CopyTo(itemArray, -1));
CollectionAssert.Equal(tempItemArray, itemArray);
}
}
[Fact]
public void CopyToIndexArrayLength()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
var tempArray = (object[]) items.Clone();
Assert.Throws<ArgumentException>(
() => collection.CopyTo(items, collection.Count));
CollectionAssert.Equal(tempArray, items);
}
[Fact]
public void CopyToCollectionLargerThanArray()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
object[] itemArray = GenerateItems(collection.Count + 1);
var tempItemArray = (object[]) itemArray.Clone();
Assert.Throws<ArgumentException>(
() => collection.CopyTo(itemArray, 2));
CollectionAssert.Equal(tempItemArray, itemArray);
}
[Fact]
public void CopyToMDArray()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
Assert.Throws<ArgumentException>(
() =>
collection.CopyTo(new object[1, collection.Count], 0));
}
protected void AssertThrows(
Type[] exceptionTypes,
Action testCode)
{
Exception exception = Record.Exception(testCode);
if (exception == null)
{
throw new AssertActualExpectedException(
exceptionTypes,
null,
"Expected an exception but got null.");
}
Type exceptionType = exception.GetType();
if (!exceptionTypes.Contains(exceptionType))
{
throw new AssertActualExpectedException(
exceptionTypes,
exceptionType,
"Caught wrong exception.");
}
}
[Fact]
public void CopyToInvalidTypes()
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
Type[] expectedExceptionTypes = IsGenericCompatibility
? new[]
{
typeof (
ArgumentException),
typeof (
InvalidCastException
)
}
: new[]
{
typeof (
ArgumentException)
};
foreach (Type type in InvalidArrayTypes)
{
Array itemArray = Array.CreateInstance(
type,
collection.Count);
var tempItemArray = (Array) itemArray.Clone();
AssertThrows(
expectedExceptionTypes,
() => collection.CopyTo(itemArray, 0));
CollectionAssert.Equal(tempItemArray, itemArray);
}
}
[Theory]
[InlineData(16, 20, -5, -1)]
[InlineData(16, 21, -4, 1)]
[InlineData(16, 20, 0, 0)]
[InlineData(16, 20, 0, 4)]
[InlineData(16, 24, 0, 4)]
public void CopyTo(
int size,
int arraySize,
int arrayLowerBound,
int copyToIndex)
{
if (arrayLowerBound != 0 && !PlatformDetection.IsNonZeroLowerBoundArraySupported)
return;
object[] items = GenerateItems(size);
ICollection collection = GetCollection(items);
Array itemArray = Array.CreateInstance(
typeof (object),
new[] {arraySize},
new[] {arrayLowerBound});
var tempItemArray = (Array) itemArray.Clone();
if (CopyToOnlySupportsZeroLowerBounds
&& arrayLowerBound != 0)
{
Assert.Throws<ArgumentException>(
() => collection.CopyTo(itemArray, copyToIndex));
}
else
{
collection.CopyTo(itemArray, copyToIndex);
Array.Copy(
items,
0,
tempItemArray,
copyToIndex,
items.Length);
CollectionAssert.Equal(tempItemArray, itemArray);
}
}
[Fact]
public void CopyToValidTypes()
{
foreach (Type type in ValidArrayTypes)
{
object[] items = GenerateItems(16);
ICollection collection = GetCollection(items);
Array itemArray = Array.CreateInstance(
type,
collection.Count);
collection.CopyTo(itemArray, 0);
CollectionAssert.Equal(items, itemArray);
}
}
[Fact]
public void CollectionShouldContainAllItems()
{
object[] items = GenerateItems(16);
ICollection<T> collection = GetCollection(items) as ICollection<T>;
if (collection == null)
return;
Assert.All(items, item => Assert.True(collection.Contains((T) item)));
}
internal class MyInvalidReferenceType
{
}
internal struct MyInvalidValueType
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Codex.Storage.Utilities;
using Nest;
namespace Codex.Storage.ElasticProviders
{
/// <summary>
/// Helper class with custom analyzers.
/// </summary>
internal static class CustomAnalyzers
{
/// <summary>
/// Project name analyzer which lowercases project name
/// </summary>
public static CustomAnalyzer LowerCaseKeywordAnalyzer { get; } = new CustomAnalyzer
{
Filter = new List<string>
{
// (built in) normalize to lowercase
"lowercase",
},
Tokenizer = "keyword",
};
/// <summary>
/// Project name analyzer which lowercases project name
/// </summary>
public static CustomNormalizer LowerCaseKeywordNormalizer { get; } = new CustomNormalizer
{
Filter = new List<string>
{
// (built in) normalize to lowercase
"lowercase",
// (built in) normalize to ascii equivalents
"asciifolding",
},
};
/// <summary>
/// NGramAnalyzer is useful for "partial name search".
/// </summary>
public static CustomAnalyzer PrefixFilterIdentifierNGramAnalyzer { get; } = new CustomAnalyzer
{
Filter = new List<string>
{
"name_gram_delimiter_start_inserter",
"name_gram_delimiter_inserter",
"name_gram_prefix_delimiter_processor",
"code_preprocess_gram",
"name_gram_delimiter_exclusion",
"unique",
"name_gram_delimiter_remover",
// Camel case is superceded by name_gram_delimiter_inserter, which
// seems to put a delimiter at all the right places
// does not help with a sequence of digits but that probably doesn't matter
//"camel_case_filter",
"name_gram_length_exclusion",
// (built in) normalize to lowercase
"lowercase",
// (built in) Only pass unique tokens to name_ngrams to prevent excessive proliferation of tokens
"unique",
"name_ngrams",
// Remove 3 character strings with the first character '^'
// which is only the prefix marker character
// Since that means there are only 2 actual searchable characters (3 searchable characters is required)
"prefix_min_length_remover",
"name_gram_length_exclusion",
// (built in) normalize to ascii equivalents
"asciifolding",
// (built in) Finally only index unique tokens
"unique",
},
Tokenizer = "keyword",
};
public static CustomAnalyzer PrefixFilterFullNameNGramAnalyzer { get; } = new CustomAnalyzer
{
Filter = new List<string>
{
"leading_dot_inserter",
"code_preprocess_gram",
"leading_dot_full_name_only_exclusion",
"name_gram_length_exclusion",
// TODO: All the filters above here could be replaced with path_hierarchy tokenizer with delimiter '.' and reverse=true.
// (built in) normalize to lowercase
"lowercase",
// (built in) normalize to ascii equivalents
"asciifolding",
// (built in) Only pass unique tokens to name_ngrams to prevent excessive proliferation of tokens
"unique",
},
Tokenizer = "keyword",
};
public static CustomAnalyzer EncodedFullTextAnalyzer { get; } = new CustomAnalyzer
{
Filter = new List<string>
{
"standard",
"lowercase",
},
Tokenizer = "standard",
CharFilter = new List<string>
{
"punctuation_to_space_replacement",
"remove_line_encoding"
}
};
public static readonly IDictionary<string, ITokenizer> TokenizersMap = new Dictionary<string, ITokenizer>()
{
{
// Ex. Turns [one.two.three] into [one.two.three, two.three, three]
"end_edge_dot_hierarchy",
new PathHierarchyTokenizer()
{
Delimiter = '.',
Reverse = true,
}
},
{
// Ex. Turns [one@two@three] into [one@two@three, two@three, three]
"end_edge_at_hierarchy",
new PathHierarchyTokenizer()
{
Delimiter = '@',
Reverse = true,
}
}
};
public static readonly IDictionary<string, ICharFilter> CharFiltersMap = new Dictionary<string, ICharFilter>()
{
{
// Replace punctuation (i.e. '.' or ',') characters with a space
// $ ^ +=`~ <>
"punctuation_to_space_replacement",
new PatternReplaceCharFilter()
{
Pattern = "[$^+=`~<>!\"#%&'()*,-./:;?@\\[\\]\\\\_{}]",
//Pattern = $"[{Regex.Escape("!\"#%&'()*,-./:;?@[\\]_{}")}]",
Replacement = " "
}
},
{
// Remove encoded line numbers
"remove_line_encoding",
new PatternReplaceCharFilter()
{
Pattern = FullTextUtilities.EncodeLineSpecifier("\\d+"),
Replacement = ""
}
}
};
public static readonly IDictionary<string, ITokenFilter> FiltersMap = new Dictionary<string, ITokenFilter>()
{
{
// Add '@^' symbols at the beginning of string
"name_gram_delimiter_start_inserter",
new PatternReplaceTokenFilter()
{
Pattern = "^(.*)",
Replacement = "@\\^$1^"
}
},
{
// Add @ symbol before upper to lower case transition
"name_gram_delimiter_inserter",
new PatternReplaceTokenFilter()
{
Pattern = "(?:(?<leading>\\p{Lu})(?<trailing>\\p{Ll}))",
Replacement = "@${leading}${trailing}"
}
},
{
// Replace @^@ with @^ so only strict prefix always starts with ^ symbol
"name_gram_prefix_delimiter_processor",
new PatternReplaceTokenFilter()
{
Pattern = "@\\^@",
Replacement = "@\\^"
}
},
{
// Split out end aligned ngrams
"code_preprocess_gram",
new EdgeNGramTokenFilter()
{
MaxGram = MaxGram,
MinGram = MinGram,
Side = EdgeNGramSide.Back
}
},
{
// Add @ symbol before upper to lower case transition
"name_ngrams",
new EdgeNGramTokenFilter()
{
MaxGram = MaxGram,
MinGram = MinGram,
}
},
{
// Clear grams not containing @ symbol marker
// This ensures that random substrings will be removed later that
// don't mark significant name boundaries.
// Also, remove grams containing closing angle bracket,
// without opening angle bracket or starting with angle bracket
"name_gram_delimiter_exclusion",
new PatternReplaceTokenFilter()
{
Pattern = "((^[^@]*$)|(^[^@].*$)|(^[^\\<]*\\>$)|(^\\^..$))",
Replacement = ""
}
},
{
// Remove @ symbol marker in preparation for
// generating final name grams
"name_gram_delimiter_remover",
new PatternReplaceTokenFilter()
{
Pattern = "\\@",
Replacement = ""
}
},
{
// Only include full name symbols (which contain a dot other
// than the starting dot character added due to normalization
// using leading_dot_inserter)
"leading_dot_full_name_only_exclusion",
new PatternReplaceTokenFilter()
{
Pattern = "^(?<empty>)(([^\\.].*)|(\\.(?<value>.*)))$",
Replacement = "${empty}${value}"
}
},
{
// Normalize full name symbols so they all start with
// leading dot. This allows selecting only n-grams
// which contain starting dot and inner dot
// meaning the token represents a valid fragment
// of the full symbol
"leading_dot_inserter",
new PatternReplaceTokenFilter()
{
Pattern = "^.*$",
Replacement = ".$0"
}
},
{
// Remove 3 character strings with the first character '^'
// which is only the prefix marker character
// Since that means there are only 2 actual searchable characters
"prefix_min_length_remover",
new PatternReplaceTokenFilter()
{
Pattern = "(^\\^..$)",
Replacement = ""
}
},
{
// Capture camel casing groups
"camel_case_filter",
CamelCaseFilter
},
{
// Clear grams not containing @ symbol marker
// This ensures that random substrings will be removed later that
// don't mark significant name boundaries
"name_gram_length_exclusion",
new LengthTokenFilter()
{
Min = 2,
}
}
};
public static TokenFiltersDescriptor AddTokenFilters(this TokenFiltersDescriptor descriptor)
{
foreach (var tokenFilterEntry in FiltersMap)
{
descriptor = descriptor.UserDefined(tokenFilterEntry.Key, tokenFilterEntry.Value);
}
return descriptor;
}
public static CharFiltersDescriptor AddCharFilters(this CharFiltersDescriptor descriptor)
{
foreach (var charFilterEntry in CharFiltersMap)
{
descriptor = descriptor.UserDefined(charFilterEntry.Key, charFilterEntry.Value);
}
return descriptor;
}
public const string LowerCaseKeywordNormalizerName = "lowercase_keyword_norm";
public const string LowerCaseKeywordAnalyzerName = "lowercase_keyword";
public const string PrefixFilterFullNameNGramAnalyzerName = "full_name";
public const string PrefixFilterPartialNameNGramAnalyzerName = "partial_name";
public const string EncodedFullTextAnalyzerName = "encoded_full_text";
/// <summary>
/// Capture filter splits incoming sequence into the tokens that would be used by the following analysis.
/// This means that uploading the "StringBuilder" we'll get following set of indices: "str", "stri", ... "stringbuilder", "bui", "build", ... "builder.
/// To test tokenizer, you can use following query in sense:
/// <code>
/// GET testsources/_analyze?tokenizer=keyword&analyzer=partial_name { "StringBuilder"}
/// </code>
/// where 'testsources' is an index with an uploaded source.
/// </summary>
public static TokenFilterBase CamelCaseFilter => new PatternCaptureTokenFilter()
{
PreserveOriginal = true,
Patterns = new[]
{
// Lowercase sequence with at least three lower case characters
"(\\p{Lu}\\p{Lu}\\p{Lu}+)",
// Uppercase followed by lowercase then rest of word characters (NOTE: word characters include underscore '_')
"(\\p{Lu}\\p{Ll}\\w+)",
// Non-alphanumeric char (not captured) followed by series of word characters (NOTE: word characters include underscore '_')
"[^\\p{L}\\d]+(\\w+)",
// Alphanumeric char (not captured) followed by series of at least one alpha-number then series of word characters
// (NOTE: word characters include underscore '_')
"[\\p{L}\\d]([^\\p{L}\\d]+\\w+)",
// Sequence of digits
"(\\d\\d+)"
},
};
public const int MinGram = 2;
public const int MaxGram = 70;
/// <summary>
/// Func that can be used with <see cref="CreateIndexExtensions.CreateIndexAsync"/>.
/// </summary>
public static Func<IndexSettingsDescriptor, IndexSettingsDescriptor> AddNGramAnalyzerFunc { get; } =
isd => isd.Analysis(descriptor => descriptor
.TokenFilters(tfd => AddTokenFilters(tfd))
.CharFilters(cfd => AddCharFilters(cfd))
.Normalizers(bases => bases
.UserDefined(LowerCaseKeywordNormalizerName, LowerCaseKeywordNormalizer))
.Analyzers(bases => bases
.UserDefined(PrefixFilterPartialNameNGramAnalyzerName, PrefixFilterIdentifierNGramAnalyzer)
.UserDefined(PrefixFilterFullNameNGramAnalyzerName, PrefixFilterFullNameNGramAnalyzer)
.UserDefined(LowerCaseKeywordAnalyzerName, LowerCaseKeywordAnalyzer)
.UserDefined(EncodedFullTextAnalyzerName, EncodedFullTextAnalyzer)));
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System.Xml.Serialization;
namespace Amazon.S3.Model
{
/// <summary>
/// The parameters to list object versions in a bucket.
/// </summary>
[XmlTypeAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/")]
[XmlRootAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/", IsNullable = false)]
public class ListVersionsRequest : S3Request
{
#region Private Members
private string bucketName;
private string prefix;
private string keyMarker;
private string versionIdMarker;
private int maxKeys = -1;
private string delimiter;
#endregion
#region BucketName
/// <summary>
/// The name of the bucket containing the objects.
/// </summary>
[XmlElementAttribute(ElementName = "BucketName")]
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
/// <summary>
/// Sets the name of the bucket containing the objects.
/// </summary>
/// <param name="bucketName">The bucket name</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithBucketName(string bucketName)
{
this.bucketName = bucketName;
return this;
}
/// <summary>
/// Checks if BucketName property is set
/// </summary>
/// <returns>true if BucketName property is set</returns>
internal bool IsSetBucketName()
{
return !System.String.IsNullOrEmpty(this.bucketName);
}
#endregion
#region Prefix
/// <summary>
/// Selects only those keys that begin with the specified prefix.
/// </summary>
/// <remarks>
/// Prefixes can be used to separate a bucket into different groupings of keys.
/// You can think of using prefix to make groups in the same way you'd use
/// a folder in a file system.) You can use prefix with delimiter to roll
/// up numerous objects into a single result under CommonPrefixes.
/// </remarks>
[XmlElementAttribute(ElementName = "Prefix")]
public string Prefix
{
get { return this.prefix; }
set { this.prefix=value; }
}
/// <summary>
/// Selects only those keys that begin with the specified prefix.
/// </summary>
/// <remarks>
/// Prefixes can be used to separate a bucket into different groupings of keys.
/// You can think of using prefix to make groups in the same way you'd use
/// a folder in a file system.) You can use prefix with delimiter to roll
/// up numerous objects into a single result under CommonPrefixes.
/// </remarks>
/// <param name="prefix">The prefix value</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithPrefix(string prefix)
{
this.prefix = prefix;
return this;
}
/// <summary>
/// Checks if Prefix property is set
/// </summary>
/// <returns>true if Prefix property is set</returns>
internal bool IsSetPrefix()
{
return !System.String.IsNullOrEmpty(this.prefix);
}
#endregion
#region KeyMarker
/// <summary>
/// Specifies the key in the bucket that you want to start listing from.
/// </summary>
[XmlElementAttribute(ElementName = "KeyMarker")]
public string KeyMarker
{
get { return this.keyMarker; }
set { this.keyMarker = value; }
}
/// <summary>
/// Specifies the key in the bucket that you want to start listing from.
/// </summary>
/// <param name="marker">The key marker value</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithKeyMarker(string marker)
{
this.keyMarker = marker;
return this;
}
/// <summary>
/// Checks if KeyMarker property is set
/// </summary>
/// <returns>true if KeyMarker property is set</returns>
internal bool IsSetKeyMarker()
{
return !System.String.IsNullOrEmpty(KeyMarker);
}
#endregion
#region VersionIdMarker
/// <summary>
/// Specifies the object version you want to start listing from.
/// </summary>
[XmlElementAttribute(ElementName = "VersionIdMarker")]
public string VersionIdMarker
{
get { return this.versionIdMarker; }
set { this.versionIdMarker = value; }
}
/// <summary>
/// Specifies the object version you want to start listing from.
/// </summary>
/// <param name="marker">The version id marker</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithVersionIdMarker(string marker)
{
this.versionIdMarker = marker;
return this;
}
/// <summary>
/// Checks if VersionIdMarker property is set
/// </summary>
/// <returns>true if VersionIdMarker property is set</returns>
internal bool IsSetVersionIdMarker()
{
return !System.String.IsNullOrEmpty(VersionIdMarker);
}
#endregion
#region MaxKeys
/// <summary>
/// Sets the maximum number of keys returned in the response body.
/// Default: 1000.
/// </summary>
/// <remarks>
/// The response might contain fewer keys, but will never contain more.
/// If additional keys satisfy the search criteria, but were not returned
/// because max-keys was exceeded, the response object's IsTruncated
/// property will be set to True.To return the additional keys, use the
/// key-marker and version-id-marker properties on a subsequent request.
/// </remarks>
[XmlElementAttribute(ElementName = "MaxKeys")]
public int MaxKeys
{
get { return this.maxKeys; }
set { this.maxKeys = value; }
}
/// <summary>
/// Sets the maximum number of keys returned in the response body.
/// Default: 1000.
/// </summary>
/// <remarks>
/// The response might contain fewer keys, but will never contain more.
/// If additional keys satisfy the search criteria, but were not returned
/// because max-keys was exceeded, the response object's IsTruncated
/// property will be set to True.To return the additional keys, use the
/// key-marker and version-id-marker properties on a subsequent request.
/// </remarks>
/// <param name="maxKeys">The maximum keys to return</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithMaxKeys(int maxKeys)
{
this.maxKeys = maxKeys;
return this;
}
/// <summary>
/// Checks if MaxKeys property is set
/// </summary>
/// <returns>true if MaxKeys property is set</returns>
internal bool IsSetMaxKeys()
{
return this.maxKeys >= 0;
}
#endregion
#region Delimiter
/// <summary>
/// A character to group keys by.
/// </summary>
/// <remarks>
/// All keys that contain the same string between
/// the prefix and the first occurrence of the delimiter are grouped under a
/// single result element in CommonPrefixes. These groups are counted as one result
/// against the max-keys limitation. These keys are not returned elsewhere in the
/// response.
/// </remarks>
[XmlElementAttribute(ElementName = "Delimiter")]
public string Delimiter
{
get { return this.delimiter; }
set { this.delimiter = value; }
}
/// <summary>
/// A character to group keys by.
/// </summary>
/// <remarks>
/// All keys that contain the same string between
/// the prefix and the first occurrence of the delimiter are grouped under a
/// single result element in CommonPrefixes. These groups are counted as one result
/// against the max-keys limitation. These keys are not returned elsewhere in the
/// response.
/// </remarks>
/// <param name="delimiter">The delimiter value</param>
/// <returns>this instance</returns>
[System.Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ListVersionsRequest WithDelimiter(string delimiter)
{
this.delimiter = delimiter;
return this;
}
/// <summary>
/// Checks if Delimiter property is set
/// </summary>
/// <returns>true if Delimiter property is set</returns>
internal bool IsSetDelimiter()
{
return !System.String.IsNullOrEmpty(this.delimiter);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.Threading;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis
{
internal static class PerformanceCriticalCodeStageUtil
{
public static bool IsInvokedElementExpensive([CanBeNull] IMethod method)
{
var containingType = method?.GetContainingType();
if (containingType == null)
return false;
ISet<string> knownCostlyMethods = null;
var clrTypeName = containingType.GetClrName();
if (clrTypeName.Equals(KnownTypes.Component))
knownCostlyMethods = ourKnownComponentCostlyMethods;
if (clrTypeName.Equals(KnownTypes.MonoBehaviour))
knownCostlyMethods = ourKnownMonoBehaviourCostlyMethods;
if (clrTypeName.Equals(KnownTypes.GameObject))
knownCostlyMethods = ourKnownGameObjectCostlyMethods;
if (clrTypeName.Equals(KnownTypes.Resources))
knownCostlyMethods = ourKnownResourcesCostlyMethods;
if (clrTypeName.Equals(KnownTypes.Object))
knownCostlyMethods = ourKnownObjectCostlyMethods;
if (clrTypeName.Equals(KnownTypes.Transform))
knownCostlyMethods = ourKnownTransformCostlyMethods;
if (clrTypeName.Equals(KnownTypes.Debug))
knownCostlyMethods = ourKnownDebugCostlyMethods;
var shortName = method.ShortName;
if (knownCostlyMethods != null && knownCostlyMethods.Contains(shortName))
return true;
return clrTypeName.Equals(KnownTypes.GameObject) && shortName.Equals("AddComponent");
}
public static bool IsInvocationExpensive([NotNull] IInvocationExpression invocationExpression)
{
invocationExpression.GetPsiServices().Locks.AssertReadAccessAllowed();
var reference = (invocationExpression.InvokedExpression as IReferenceExpression)?.Reference;
if (reference == null)
return false;
var declaredElement = reference.Resolve().DeclaredElement as IMethod;
return IsInvokedElementExpensive(declaredElement);
}
public static bool IsCameraMainUsage(IReferenceExpression referenceExpression)
{
if (referenceExpression.NameIdentifier?.Name == "main")
{
var info = referenceExpression.Reference.Resolve();
if (info.ResolveErrorType == ResolveErrorType.OK)
{
var property = info.DeclaredElement as IProperty;
var containingType = property?.GetContainingType();
if (containingType != null && KnownTypes.Camera.Equals(containingType.GetClrName()))
{
return true;
}
}
}
return false;
}
public static bool IsNullComparisonWithUnityObject(IEqualityExpression equalityExpression, out string possibleName)
{
possibleName = null;
var reference = equalityExpression.Reference;
if (reference == null)
return false;
var isNullFound = false;
var leftOperand = equalityExpression.LeftOperand;
var rightOperand = equalityExpression.RightOperand;
if (leftOperand == null || rightOperand == null)
return false;
ICSharpExpression expression = null;
if (leftOperand.ConstantValue.IsNull())
{
isNullFound = true;
expression = rightOperand;
}
else if (rightOperand.ConstantValue.IsNull())
{
isNullFound = true;
expression = leftOperand;
}
if (!isNullFound)
return false;
var typeElement = expression.GetExpressionType().ToIType()?.GetTypeElement();
if (typeElement == null)
return false;
if (typeElement.GetAllSuperTypes().Any(t => t.GetClrName().Equals(KnownTypes.Object)))
{
var suffix = equalityExpression.EqualityType == EqualityExpressionType.NE ? "NotNull" : "Null";
string baseName;
if (expression is IReferenceExpression referenceExpression)
{
baseName = referenceExpression.NameIdentifier.Name;
}
else
{
baseName = typeElement.ShortName;
}
possibleName = "is" + baseName + suffix;
return true;
}
return false;
}
public static bool IsPerformanceCriticalRootMethod([CanBeNull] ITreeNode node)
{
if (node == null)
return false;
var typeMemberDeclaration = node as ITypeMemberDeclaration;
return IsPerformanceCriticalRootMethod(typeMemberDeclaration?.DeclaredElement);
}
public static bool IsPerformanceCriticalRootMethod([CanBeNull] IDeclaredElement declaredElement)
{
var typeMember = declaredElement as ITypeMember;
var typeElement = typeMember?.GetContainingType();
if (typeElement == null)
return false;
if (typeElement.DerivesFromMonoBehaviour() && declaredElement is IClrDeclaredElement monoBehaviorCLRDeclaredElement)
return ourKnownHotMonoBehaviourMethods.Contains(monoBehaviorCLRDeclaredElement.ShortName);
if (typeElement.DerivesFrom(KnownTypes.Editor) && declaredElement is IClrDeclaredElement editorCLRDeclaredElement)
return ourKnownHotEditorMethods.Contains(editorCLRDeclaredElement.ShortName);
if (typeElement.DerivesFrom(KnownTypes.EditorWindow) && declaredElement is IClrDeclaredElement editorWindowCLRDeclaredElement)
return ourKnownHotEditorWindowMethods.Contains(editorWindowCLRDeclaredElement.ShortName);
if (typeElement.DerivesFrom(KnownTypes.PropertyDrawer) && declaredElement is IClrDeclaredElement propertyDrawerCLRDeclaredElement)
return ourKnownHotPropertyDrawerMethods.Contains(propertyDrawerCLRDeclaredElement.ShortName);
return false;
}
#region data
private static readonly ISet<string> ourKnownHotMonoBehaviourMethods = new HashSet<string>()
{
"Update", "LateUpdate", "FixedUpdate", "OnGUI"
};
private static readonly ISet<string> ourKnownHotEditorMethods = new HashSet<string>()
{
"DrawHeader", "OnInspectorGUI", "OnInteractivePreviewGUI", "OnPreviewGUI", "OnSceneGUI"
};
private static readonly ISet<string> ourKnownHotEditorWindowMethods = new HashSet<string>()
{
"OnGUI", "OnInspectorUpdate"
};
private static readonly ISet<string> ourKnownHotPropertyDrawerMethods = new HashSet<string>()
{
"OnGUI", "GetPropertyHeight"
};
private static readonly ISet<string> ourKnownComponentCostlyMethods = new HashSet<string>()
{
"GetComponentInChildren",
"GetComponentInParent",
"GetComponentsInChildren",
"GetComponent",
"GetComponents",
"SendMessage",
"SendMessageUpwards",
"BroadcastMessage"
};
private static readonly ISet<string> ourKnownGameObjectCostlyMethods = new HashSet<string>()
{
"Find",
"FindGameObjectsWithTag",
"FindGameObjectWithTag",
"FindWithTag",
"GetComponent",
"GetComponents",
"GetComponentInChildren",
"GetComponentInParent",
"GetComponentsInChildren",
"SendMessage",
"SendMessageUpwards",
"BroadcastMessage"
};
private static readonly ISet<string> ourKnownMonoBehaviourCostlyMethods = new HashSet<string>()
{
"Invoke",
"InvokeRepeating",
"CancelInvoke",
"IsInvoking"
};
private static readonly ISet<string> ourKnownTransformCostlyMethods = new HashSet<string>()
{
"Find"
};
private static readonly ISet<string> ourKnownResourcesCostlyMethods = new HashSet<string>()
{
"FindObjectsOfTypeAll",
};
private static readonly ISet<string> ourKnownObjectCostlyMethods = new HashSet<string>()
{
"FindObjectsOfType",
"FindObjectOfType",
"FindObjectsOfTypeIncludingAssets",
};
private static readonly ISet<string> ourKnownDebugCostlyMethods = new HashSet<string>()
{
"Log",
"LogFormat",
"LogError",
"LogErrorFormat",
"LogException",
"LogWarning",
"LogWarningFormat",
"LogAssertion",
"LogAssertionFormat"
};
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class PublicKeyTests
{
private static PublicKey GetTestRsaKey()
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
return cert.PublicKey;
}
}
private static PublicKey GetTestDsaKey()
{
using (var cert = new X509Certificate2(TestData.DssCer))
{
return cert.PublicKey;
}
}
[Fact]
public static void TestOid_RSA()
{
PublicKey pk = GetTestRsaKey();
Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value);
}
[Fact]
public static void TestOid_DSA()
{
PublicKey pk = GetTestDsaKey();
Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value);
}
[Fact]
public static void TestEncodedKeyValue_RSA()
{
byte[] expectedPublicKey = (
"3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" +
"407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" +
"137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" +
"b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" +
"109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" +
"2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" +
"2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" +
"84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" +
"0b950005b14f6571c50203010001").HexToByteArray();
PublicKey pk = GetTestRsaKey();
Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData);
}
[Fact]
public static void TestEncodedKeyValue_DSA()
{
byte[] expectedPublicKey = (
"028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" +
"bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" +
"ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" +
"86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" +
"bf0963").HexToByteArray();
PublicKey pk = GetTestDsaKey();
Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData);
}
[Fact]
public static void TestEncodedParameters_RSA()
{
PublicKey pk = GetTestRsaKey();
// RSA has no key parameters, so the answer is always
// DER:NULL (type 0x05, length 0x00)
Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData);
}
[Fact]
public static void TestEncodedParameters_DSA()
{
byte[] expectedParameters = (
"3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" +
"511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" +
"986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" +
"1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" +
"B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" +
"818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" +
"584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" +
"EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" +
"DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" +
"05431D").HexToByteArray();
PublicKey pk = GetTestDsaKey();
Assert.Equal(expectedParameters, pk.EncodedParameters.RawData);
}
[Fact]
public static void TestKey_RSA()
{
using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate))
{
RSA rsa = cert.GetRSAPublicKey();
RSAParameters rsaParameters = rsa.ExportParameters(false);
byte[] expectedModulus = (
"E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" +
"51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" +
"EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" +
"C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" +
"1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" +
"94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" +
"C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" +
"E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray();
byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 };
Assert.Equal(expectedModulus, rsaParameters.Modulus);
Assert.Equal(expectedExponent, rsaParameters.Exponent);
}
}
[Fact]
public static void TestECDsaPublicKey()
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
Assert.Equal(384, publicKey.KeySize);
// The public key should be unable to sign.
Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256));
}
}
[Fact]
public static void TestECDsaPublicKey_ValidatesSignature()
{
// This signature was produced as the output of ECDsaCng.SignData with the same key
// on .NET 4.6. Ensure it is verified here as a data compatibility test.
//
// Note that since ECDSA signatures contain randomness as an input, this value is unlikely
// to be reproduced by another equivalent program.
byte[] existingSignature =
{
// r:
0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27,
0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6,
0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3,
0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11,
0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5,
0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F,
// s:
0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E,
0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34,
0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3,
0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB,
0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93,
0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96,
};
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
Assert.Equal(384, publicKey.KeySize);
bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256);
Assert.True(isSignatureValid, "isSignatureValid");
}
}
[Fact]
public static void TestECDsaPublicKey_NonSignatureCert()
{
using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
// It is an Elliptic Curve Cryptography public key.
Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);
// But, due to KeyUsage, it shouldn't be used for ECDSA.
Assert.Null(publicKey);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void TestKey_ECDsaCng256()
{
TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void TestKey_ECDsaCng384()
{
TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void TestKey_ECDsaCng521()
{
TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey);
}
private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected)
{
#if !NETNATIVE
using (X509Certificate2 cert = new X509Certificate2(certBytes))
{
ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey());
CngKey k = e.Key;
byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob);
using (BinaryReader br = new BinaryReader(new MemoryStream(blob)))
{
int magic = br.ReadInt32();
int cbKey = br.ReadInt32();
Assert.Equal(expected.QX.Length, cbKey);
byte[] qx = br.ReadBytes(cbKey);
byte[] qy = br.ReadBytes(cbKey);
Assert.Equal<byte>(expected.QX, qx);
Assert.Equal<byte>(expected.QY, qy);
}
}
#endif //!NETNATIVE
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Diagnostics;
namespace Irony.Parsing
{
/// <summary>
/// Parser class represents combination of scanner and LALR parser (CoreParser)
/// </summary>
public class Parser
{
public readonly ParserData Data;
public readonly LanguageData Language;
public readonly NonTerminal Root;
//public readonly CoreParser CoreParser;
public readonly Scanner Scanner;
/// <summary>
/// Either language root or initial state for parsing snippets - like Ruby's expressions in strings : "result= #{x+y}"
/// </summary>
internal readonly ParserState InitialState;
private readonly Grammar grammar;
public Parser(Grammar grammar) : this(new LanguageData(grammar))
{ }
public Parser(LanguageData language) : this(language, null)
{ }
public Parser(LanguageData language, NonTerminal root)
{
this.Language = language;
this.Data = Language.ParserData;
this.grammar = Language.Grammar;
this.Context = new ParsingContext(this);
this.Scanner = new Scanner(this);
this.Root = root;
if (Root == null)
{
this.Root = this.Language.Grammar.Root;
this.InitialState = this.Language.ParserData.InitialState;
}
else
{
if (this.Root != this.Language.Grammar.Root && !this.Language.Grammar.SnippetRoots.Contains(this.Root))
throw new Exception(string.Format(Resources.ErrRootNotRegistered, root.Name));
this.InitialState = this.Language.ParserData.InitialStates[this.Root];
}
}
public ParsingContext Context { get; internal set; }
public ParseTree Parse(string sourceText)
{
return Parse(sourceText, "Source");
}
public ParseTree Parse(string sourceText, string fileName)
{
var loc = default(SourceLocation);
this.Reset();
/*if (Context.Status == ParserStatus.AcceptedPartial)
{
var oldLoc = Context.Source.Location;
loc = new SourceLocation(oldLoc.Position, oldLoc.Line + 1, 0);
} else { }
}*/
this.Context.Source = new SourceStream(sourceText, this.Language.Grammar.CaseSensitive, this.Context.TabWidth, loc);
this.Context.CurrentParseTree = new ParseTree(sourceText, fileName);
this.Context.Status = ParserStatus.Parsing;
var sw = new Stopwatch();
sw.Start();
this.ParseAll();
// Set Parse status
var parseTree = Context.CurrentParseTree;
var hasErrors = parseTree.HasErrors();
if (hasErrors)
parseTree.Status = ParseTreeStatus.Error;
else if (Context.Status == ParserStatus.AcceptedPartial)
parseTree.Status = ParseTreeStatus.Partial;
else
parseTree.Status = ParseTreeStatus.Parsed;
// Build AST if no errors and AST flag is set
bool createAst = this.grammar.LanguageFlags.IsSet(LanguageFlags.CreateAst);
if (createAst && !hasErrors)
this.Language.Grammar.BuildAst(this.Language, parseTree);
// Done; record the time
sw.Stop();
parseTree.ParseTimeMilliseconds = sw.ElapsedMilliseconds;
if (parseTree.ParserMessages.Count > 0)
parseTree.ParserMessages.Sort(LogMessageList.ByLocation);
return parseTree;
}
public ParseTree ScanOnly(string sourceText, string fileName)
{
this.Context.CurrentParseTree = new ParseTree(sourceText, fileName);
this.Context.Source = new SourceStream(sourceText, this.Language.Grammar.CaseSensitive, this.Context.TabWidth);
while (true)
{
var token = this.Scanner.GetToken();
if (token == null || token.Terminal == this.Language.Grammar.Eof)
break;
}
return this.Context.CurrentParseTree;
}
internal void Reset()
{
this.Context.Reset();
Scanner.Reset();
}
private void ParseAll()
{
// Main loop
this.Context.Status = ParserStatus.Parsing;
while (this.Context.Status == ParserStatus.Parsing)
{
this.ExecuteNextAction();
}
}
#region Parser Action execution
internal ParserAction GetNextAction()
{
var currState = this.Context.CurrentParserState;
var currInput = this.Context.CurrentParserInput;
if (currState.DefaultAction != null)
return currState.DefaultAction;
ParserAction action;
// First try as keyterm/key symbol; for example if token text = "while", then first try it as a keyword "while";
// if this does not work, try as an identifier that happens to match a keyword but is in fact identifier
Token inputToken = currInput.Token;
if (inputToken != null && inputToken.KeyTerm != null)
{
var keyTerm = inputToken.KeyTerm;
if (currState.Actions.TryGetValue(keyTerm, out action))
{
#region comments
// Ok, we found match as a key term (keyword or special symbol)
// Backpatch the token's term. For example in most cases keywords would be recognized as Identifiers by Scanner.
// Identifier would also check with SymbolTerms table and set AsSymbol field to SymbolTerminal if there exist
// one for token content. So we first find action by Symbol if there is one; if we find action, then we
// patch token's main terminal to AsSymbol value. This is important for recognizing keywords (for colorizing),
// and for operator precedence algorithm to work when grammar uses operators like "AND", "OR", etc.
//TODO: This might be not quite correct action, and we can run into trouble with some languages that have keywords that
// are not reserved words. But proper implementation would require substantial addition to parser code:
// when running into errors, we need to check the stack for places where we made this "interpret as Symbol"
// decision, roll back the stack and try to reinterpret as identifier
#endregion comments
inputToken.SetTerminal(keyTerm);
currInput.Term = keyTerm;
currInput.Precedence = keyTerm.Precedence;
currInput.Associativity = keyTerm.Associativity;
return action;
}
}
// Try to get by main Terminal, only if it is not the same as symbol
if (currState.Actions.TryGetValue(currInput.Term, out action))
return action;
// If input is EOF and NewLineBeforeEof flag is set, try using NewLine to find action
if (currInput.Term == this.grammar.Eof &&
this.grammar.LanguageFlags.IsSet(LanguageFlags.NewLineBeforeEOF) &&
currState.Actions.TryGetValue(this.grammar.NewLine, out action))
{
// There's no action for EOF but there's action for NewLine. Let's add newLine token as input, just in case
// action code wants to check input - it should see NewLine.
var newLineToken = new Token(this.grammar.NewLine, currInput.Token.Location, "\r\n", null);
var newLineNode = new ParseTreeNode(newLineToken);
this.Context.CurrentParserInput = newLineNode;
return action;
}
return null;
}
private void ExecuteNextAction()
{
// Read input only if DefaultReduceAction is null - in this case the state does not contain ExpectedSet,
// so parser cannot assist scanner when it needs to select terminal and therefore can fail
if (this.Context.CurrentParserInput == null && this.Context.CurrentParserState.DefaultAction == null)
this.ReadInput();
// Check scanner error
if (this.Context.CurrentParserInput != null && this.Context.CurrentParserInput.IsError)
{
this.RecoverFromError();
return;
}
// Try getting action
var action = this.GetNextAction();
if (action == null)
{
if (this.CheckPartialInputCompleted())
return;
this.RecoverFromError();
return;
}
// We have action. Write trace and execute it
if (this.Context.TracingEnabled)
this.Context.AddTrace(action.ToString());
action.Execute(this.Context);
}
#endregion Parser Action execution
#region reading input
public void ReadInput()
{
Token token;
Terminal term;
// Get token from scanner while skipping all comment tokens (but accumulating them in comment block)
do
{
token = Scanner.GetToken();
term = token.Terminal;
if (term.Category == TokenCategory.Comment)
this.Context.CurrentCommentTokens.Add(token);
}
while (term.Flags.IsSet(TermFlags.IsNonGrammar) && term != this.grammar.Eof);
// Check brace token
if (term.Flags.IsSet(TermFlags.IsBrace) && !CheckBraceToken(token))
token = new Token(this.grammar.SyntaxError, token.Location, token.Text, string.Format(Resources.ErrUnmatchedCloseBrace, token.Text));
// Create parser input node
this.Context.CurrentParserInput = new ParseTreeNode(token);
// Attach comments if any accumulated to content token
if (token.Terminal.Category == TokenCategory.Content)
{
this.Context.CurrentParserInput.Comments = this.Context.CurrentCommentTokens;
this.Context.CurrentCommentTokens = new TokenList();
}
// Fire event on Terminal
token.Terminal.OnParserInputPreview(this.Context);
}
#endregion reading input
#region Error Recovery
public void RecoverFromError()
{
this.Data.ErrorAction.Execute(this.Context);
}
#endregion Error Recovery
#region Utilities
/// <summary>
/// We assume here that the token is a brace (opening or closing)
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
private bool CheckBraceToken(Token token)
{
if (token.Terminal.Flags.IsSet(TermFlags.IsOpenBrace))
{
this.Context.OpenBraces.Push(token);
return true;
}
// It is closing brace; check if we have opening brace in the stack
var braces = this.Context.OpenBraces;
var match = (braces.Count > 0 && braces.Peek().Terminal.IsPairFor == token.Terminal);
if (!match)
return false;
// Link both tokens, pop the stack and return true
var openingBrace = braces.Pop();
openingBrace.OtherBrace = token;
token.OtherBrace = openingBrace;
return true;
}
private bool CheckPartialInputCompleted()
{
bool partialCompleted = (this.Context.Mode == ParseMode.CommandLine && this.Context.CurrentParserInput.Term == this.grammar.Eof);
if (!partialCompleted)
return false;
this.Context.Status = ParserStatus.AcceptedPartial;
// clean up EOF in input so we can continue parsing next line
this.Context.CurrentParserInput = null;
return true;
}
#endregion Utilities
}
}
| |
#if !UNITY_METRO
#define UTT_SOCKETS_SUPPORTED
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
#if UTT_SOCKETS_SUPPORTED
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
#endif
#if UNITY_EDITOR
using UnityEditorInternal;
#endif
namespace UnityTest
{
public class TestRunnerConfigurator
{
public static string integrationTestsNetwork = "networkconfig.txt";
public static string batchRunFileMarker = "batchrun.txt";
public static string testScenesToRun = "testscenes.txt";
public static string previousScenes = "previousScenes.txt";
public bool isBatchRun { get; private set; }
public bool sendResultsOverNetwork { get; private set; }
#if UTT_SOCKETS_SUPPORTED
private readonly List<IPEndPoint> m_IPEndPointList = new List<IPEndPoint>();
#endif
public TestRunnerConfigurator()
{
CheckForBatchMode();
CheckForSendingResultsOverNetwork();
}
#if UNITY_EDITOR
public UnityEditor.EditorBuildSettingsScene[] GetPreviousScenesToRestore()
{
string text = null;
if (Application.isEditor)
{
text = GetTextFromTempFile(previousScenes);
}
if(text != null)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(UnityEditor.EditorBuildSettingsScene[]));
using(var textReader = new StringReader(text))
{
try
{
return (UnityEditor.EditorBuildSettingsScene[] )serializer.Deserialize(textReader);
}
catch (System.Xml.XmlException)
{
return null;
}
}
}
return null;
}
#endif
public string GetIntegrationTestScenes(int testSceneNum)
{
string text;
if (Application.isEditor)
text = GetTextFromTempFile(testScenesToRun);
else
text = GetTextFromTextAsset(testScenesToRun);
List<string> sceneList = new List<string>();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
sceneList.Add(line.ToString());
}
if (testSceneNum < sceneList.Count)
return sceneList.ElementAt(testSceneNum);
else
return null;
}
private void CheckForSendingResultsOverNetwork()
{
#if UTT_SOCKETS_SUPPORTED
string text;
if (Application.isEditor)
text = GetTextFromTempFile(integrationTestsNetwork);
else
text = GetTextFromTextAsset(integrationTestsNetwork);
if (text == null) return;
sendResultsOverNetwork = true;
m_IPEndPointList.Clear();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
var idx = line.IndexOf(':');
if (idx == -1) throw new Exception(line);
var ip = line.Substring(0, idx);
var port = line.Substring(idx + 1);
m_IPEndPointList.Add(new IPEndPoint(IPAddress.Parse(ip), Int32.Parse(port)));
}
#endif // if UTT_SOCKETS_SUPPORTED
}
private static string GetTextFromTextAsset(string fileName)
{
var nameWithoutExtension = fileName.Substring(0, fileName.LastIndexOf('.'));
var resultpathFile = Resources.Load(nameWithoutExtension) as TextAsset;
return resultpathFile != null ? resultpathFile.text : null;
}
private static string GetTextFromTempFile(string fileName)
{
string text = null;
try
{
#if UNITY_EDITOR && !UNITY_WEBPLAYER
text = File.ReadAllText(Path.Combine("Temp", fileName));
#endif
}
catch
{
return null;
}
return text;
}
private void CheckForBatchMode()
{
#if IMITATE_BATCH_MODE
isBatchRun = true;
#elif UNITY_EDITOR
if (Application.isEditor && InternalEditorUtility.inBatchMode)
isBatchRun = true;
#else
if (GetTextFromTextAsset(batchRunFileMarker) != null) isBatchRun = true;
#endif
}
public static List<string> GetAvailableNetworkIPs()
{
#if UTT_SOCKETS_SUPPORTED
if (!NetworkInterface.GetIsNetworkAvailable())
return new List<String>{IPAddress.Loopback.ToString()};
var ipList = new List<UnicastIPAddressInformation>();
var allIpsList = new List<UnicastIPAddressInformation>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (netInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
netInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
continue;
var ipAdresses = netInterface.GetIPProperties().UnicastAddresses
.Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork);
allIpsList.AddRange(ipAdresses);
if (netInterface.OperationalStatus != OperationalStatus.Up) continue;
ipList.AddRange(ipAdresses);
}
//On Mac 10.10 all interfaces return OperationalStatus.Unknown, thus this workaround
if(!ipList.Any()) return allIpsList.Select(i => i.Address.ToString()).ToList();
// sort ip list by their masks to predict which ip belongs to lan network
ipList.Sort((ip1, ip2) =>
{
var mask1 = BitConverter.ToInt32(ip1.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
var mask2 = BitConverter.ToInt32(ip2.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
return mask2.CompareTo(mask1);
});
if (ipList.Count == 0)
return new List<String> { IPAddress.Loopback.ToString() };
return ipList.Select(i => i.Address.ToString()).ToList();
#else
return new List<string>();
#endif // if UTT_SOCKETS_SUPPORTED
}
public ITestRunnerCallback ResolveNetworkConnection()
{
#if UTT_SOCKETS_SUPPORTED
var nrsList = m_IPEndPointList.Select(ipEndPoint => new NetworkResultSender(ipEndPoint.Address.ToString(), ipEndPoint.Port)).ToList();
var timeout = TimeSpan.FromSeconds(30);
DateTime startTime = DateTime.Now;
while ((DateTime.Now - startTime) < timeout)
{
foreach (var networkResultSender in nrsList)
{
try
{
if (!networkResultSender.Ping()) continue;
}
catch (Exception e)
{
Debug.LogException(e);
sendResultsOverNetwork = false;
return null;
}
return networkResultSender;
}
Thread.Sleep(500);
}
Debug.LogError("Couldn't connect to the server: " + string.Join(", ", m_IPEndPointList.Select(ipep => ipep.Address + ":" + ipep.Port).ToArray()));
sendResultsOverNetwork = false;
#endif // if UTT_SOCKETS_SUPPORTED
return null;
}
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Tests.Dataload
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Datastream;
using NUnit.Framework;
/// <summary>
/// Data streamer tests.
/// </summary>
public sealed class DataStreamerTest
{
/** Cache name. */
private const string CacheName = "partitioned";
/** Node. */
private IIgnite _grid;
/** Node 2. */
private IIgnite _grid2;
/** Cache. */
private ICache<int, int?> _cache;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
_grid = Ignition.Start(TestUtils.GetTestConfiguration());
_grid2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid1"
});
_cache = _grid.CreateCache<int, int?>(CacheName);
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
for (int i = 0; i < 100; i++)
_cache.Remove(i);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid);
}
/// <summary>
/// Test data streamer property configuration. Ensures that at least no exceptions are thrown.
/// </summary>
[Test]
public void TestPropertyPropagation()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.AreEqual(CacheName, ldr.CacheName);
Assert.AreEqual(0, ldr.AutoFlushFrequency);
Assert.IsFalse(ldr.AllowOverwrite);
ldr.AllowOverwrite = true;
Assert.IsTrue(ldr.AllowOverwrite);
ldr.AllowOverwrite = false;
Assert.IsFalse(ldr.AllowOverwrite);
Assert.IsFalse(ldr.SkipStore);
ldr.SkipStore = true;
Assert.IsTrue(ldr.SkipStore);
ldr.SkipStore = false;
Assert.IsFalse(ldr.SkipStore);
Assert.AreEqual(DataStreamerDefaults.DefaultPerNodeBufferSize, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 1;
Assert.AreEqual(1, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 2;
Assert.AreEqual(2, ldr.PerNodeBufferSize);
Assert.AreEqual(DataStreamerDefaults.DefaultPerThreadBufferSize, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 1;
Assert.AreEqual(1, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 2;
Assert.AreEqual(2, ldr.PerThreadBufferSize);
Assert.AreEqual(0, ldr.PerNodeParallelOperations);
var ops = DataStreamerDefaults.DefaultParallelOperationsMultiplier *
IgniteConfiguration.DefaultThreadPoolSize;
ldr.PerNodeParallelOperations = ops;
Assert.AreEqual(ops, ldr.PerNodeParallelOperations);
ldr.PerNodeParallelOperations = 2;
Assert.AreEqual(2, ldr.PerNodeParallelOperations);
Assert.AreEqual(DataStreamerDefaults.DefaultTimeout, ldr.Timeout);
ldr.Timeout = TimeSpan.MaxValue;
Assert.AreEqual(TimeSpan.MaxValue, ldr.Timeout);
ldr.Timeout = TimeSpan.FromSeconds(1.5);
Assert.AreEqual(1.5, ldr.Timeout.TotalSeconds);
}
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemove()
{
IDataStreamer<int, int> ldr;
using (ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.IsFalse(ldr.Task.IsCompleted);
ldr.AllowOverwrite = true;
// Additions.
var task = ldr.AddData(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(ldr.Task.IsCompleted);
task = ldr.AddData(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
Assert.IsTrue(task.IsCompleted);
task = ldr.AddData(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.IsTrue(task.IsCompleted);
// Removal.
task = ldr.RemoveData(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
Assert.IsTrue(task.IsCompleted);
// Mixed.
ldr.AddData(5, 5);
ldr.RemoveData(2);
ldr.AddData(new KeyValuePair<int, int>(7, 7));
ldr.AddData(6, 6);
ldr.RemoveData(4);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.AddData(new KeyValuePair<int, int>(8, 8));
ldr.RemoveData(3);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
Assert.IsTrue(ldr.Task.IsCompleted);
}
/// <summary>
/// Tests object graphs with loops.
/// </summary>
[Test]
public void TestObjectGraphs()
{
var obj1 = new Container();
var obj2 = new Container();
var obj3 = new Container();
var obj4 = new Container();
obj1.Inner = obj2;
obj2.Inner = obj1;
obj3.Inner = obj1;
obj4.Inner = new Container();
using (var ldr = _grid.GetDataStreamer<int, Container>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.AddData(1, obj1);
ldr.AddData(2, obj2);
ldr.AddData(3, obj3);
ldr.AddData(4, obj4);
}
var cache = _grid.GetCache<int, Container>(CacheName);
var res = cache[1];
Assert.AreEqual(res, res.Inner.Inner);
Assert.IsNotNull(cache[2].Inner);
Assert.IsNotNull(cache[2].Inner.Inner);
Assert.IsNotNull(cache[3].Inner);
Assert.IsNotNull(cache[3].Inner.Inner);
Assert.IsNotNull(cache[4].Inner);
Assert.IsNull(cache[4].Inner.Inner);
}
/// <summary>
/// Test "tryFlush".
/// </summary>
[Test]
public void TestTryFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.TryFlush();
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test buffer size adjustments.
/// </summary>
[Test]
public void TestBufferSize()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
const int timeout = 5000;
var part1 = GetPrimaryPartitionKeys(_grid, 4);
var part2 = GetPrimaryPartitionKeys(_grid2, 4);
var task = ldr.AddData(part1[0], part1[0]);
Thread.Sleep(100);
Assert.IsFalse(task.IsCompleted);
ldr.PerNodeBufferSize = 2;
ldr.PerThreadBufferSize = 1;
ldr.AddData(part2[0], part2[0]);
ldr.AddData(part1[1], part1[1]);
Assert.IsTrue(ldr.AddData(part2[1], part2[1]).Wait(timeout));
Assert.IsTrue(task.Wait(timeout));
Assert.AreEqual(part1[0], _cache.Get(part1[0]));
Assert.AreEqual(part1[1], _cache.Get(part1[1]));
Assert.AreEqual(part2[0], _cache.Get(part2[0]));
Assert.AreEqual(part2[1], _cache.Get(part2[1]));
Assert.IsTrue(ldr.AddData(new[]
{
new KeyValuePair<int, int>(part1[2], part1[2]),
new KeyValuePair<int, int>(part1[3], part1[3]),
new KeyValuePair<int, int>(part2[2], part2[2]),
new KeyValuePair<int, int>(part2[3], part2[3])
}).Wait(timeout));
Assert.AreEqual(part1[2], _cache.Get(part1[2]));
Assert.AreEqual(part1[3], _cache.Get(part1[3]));
Assert.AreEqual(part2[2], _cache.Get(part2[2]));
Assert.AreEqual(part2[3], _cache.Get(part2[3]));
}
}
/// <summary>
/// Gets the primary partition keys.
/// </summary>
private static int[] GetPrimaryPartitionKeys(IIgnite ignite, int count)
{
var affinity = ignite.GetAffinity(CacheName);
var localNode = ignite.GetCluster().GetLocalNode();
var part = affinity.GetPrimaryPartitions(localNode).First();
return Enumerable.Range(0, int.MaxValue)
.Where(k => affinity.GetPartition(k) == part)
.Take(count)
.ToArray();
}
/// <summary>
/// Test close.
/// </summary>
[Test]
public void TestClose()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.Close(false);
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test close with cancellation.
/// </summary>
[Test]
public void TestCancel()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.Close(true);
fut.Wait();
Assert.IsFalse(_cache.ContainsKey(1));
}
}
/// <summary>
/// Tests that streamer gets collected when there are no references to it.
/// </summary>
[Test]
[Ignore("IGNITE-8731")]
public void TestFinalizer()
{
var streamer = _grid.GetDataStreamer<int, int>(CacheName);
var streamerRef = new WeakReference(streamer);
Assert.IsNotNull(streamerRef.Target);
// ReSharper disable once RedundantAssignment
streamer = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(streamerRef.Target);
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.AddData(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.AddData(2, 2);
ldr.AutoFlushFrequency = long.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.AddData(3, 3);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test flush before stop.
fut = ldr.AddData(4, 4);
ldr.AutoFlushFrequency = 0;
fut.Wait();
// Test flush after second turn on.
fut = ldr.AddData(5, 5);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
}
/// <summary>
/// Test multithreaded behavior.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestMultithreaded()
{
int entriesPerThread = 100000;
int threadCnt = 8;
for (int i = 0; i < 5; i++)
{
_cache.Clear();
Assert.AreEqual(0, _cache.GetSize());
Stopwatch watch = new Stopwatch();
watch.Start();
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.PerNodeBufferSize = 1024;
int ctr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref ctr);
int startIdx = (threadIdx - 1) * entriesPerThread;
int endIdx = startIdx + entriesPerThread;
for (int j = startIdx; j < endIdx; j++)
{
// ReSharper disable once AccessToDisposedClosure
ldr.AddData(j, j);
if (j % 100000 == 0)
Console.WriteLine("Put [thread=" + threadIdx + ", cnt=" + j + ']');
}
}, threadCnt);
}
Console.WriteLine("Iteration " + i + ": " + watch.ElapsedMilliseconds);
watch.Reset();
for (int j = 0; j < threadCnt * entriesPerThread; j++)
Assert.AreEqual(j, j);
}
}
/// <summary>
/// Tests custom receiver.
/// </summary>
[Test]
public void TestStreamReceiver()
{
TestStreamReceiver(new StreamReceiverBinarizable());
TestStreamReceiver(new StreamReceiverSerializable());
}
/// <summary>
/// Tests StreamVisitor.
/// </summary>
[Test]
public void TestStreamVisitor()
{
#if !NETCOREAPP // Serializing delegates is not supported on this platform.
TestStreamReceiver(new StreamVisitor<int, int>((c, e) => c.Put(e.Key, e.Value + 1)));
#endif
}
/// <summary>
/// Tests StreamTransformer.
/// </summary>
[Test]
public void TestStreamTransformer()
{
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorSerializable()));
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorBinarizable()));
}
[Test]
public void TestStreamTransformerIsInvokedForDuplicateKeys()
{
var cache = _grid.GetOrCreateCache<string, long>("c");
using (var streamer = _grid.GetDataStreamer<string, long>(cache.Name))
{
streamer.AllowOverwrite = true;
streamer.Receiver = new StreamTransformer<string, long, object, object>(new CountingEntryProcessor());
var words = Enumerable.Repeat("a", 3).Concat(Enumerable.Repeat("b", 2));
foreach (var word in words)
{
streamer.AddData(word, 1L);
}
}
Assert.AreEqual(3, cache.Get("a"));
Assert.AreEqual(2, cache.Get("b"));
}
/// <summary>
/// Tests specified receiver.
/// </summary>
private void TestStreamReceiver(IStreamReceiver<int, int> receiver)
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Receiver = new StreamReceiverBinarizable();
ldr.Receiver = receiver; // check double assignment
Assert.AreEqual(ldr.Receiver, receiver);
for (var i = 0; i < 100; i++)
ldr.AddData(i, i);
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, _cache.Get(i));
}
}
/// <summary>
/// Tests the stream receiver in keepBinary mode.
/// </summary>
[Test]
public void TestStreamReceiverKeepBinary()
{
// ReSharper disable once LocalVariableHidesMember
var cache = _grid.GetCache<int, BinarizableEntry>(CacheName);
using (var ldr0 = _grid.GetDataStreamer<int, int>(CacheName))
using (var ldr = ldr0.WithKeepBinary<int, IBinaryObject>())
{
ldr.Receiver = new StreamReceiverKeepBinary();
ldr.AllowOverwrite = true;
for (var i = 0; i < 100; i++)
ldr.AddData(i, _grid.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry {Val = i}));
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, cache.Get(i).Val);
// Repeating WithKeepBinary call: valid args.
Assert.AreSame(ldr, ldr.WithKeepBinary<int, IBinaryObject>());
// Invalid type args.
var ex = Assert.Throws<InvalidOperationException>(() => ldr.WithKeepBinary<string, IBinaryObject>());
Assert.AreEqual(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.", ex.Message);
}
}
/// <summary>
/// Test binarizable receiver.
/// </summary>
private class StreamReceiverBinarizable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test binary receiver.
/// </summary>
[Serializable]
private class StreamReceiverKeepBinary : IStreamReceiver<int, IBinaryObject>
{
/** <inheritdoc /> */
public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries)
{
var binary = cache.Ignite.GetBinary();
cache.PutAll(entries.ToDictionary(x => x.Key, x =>
binary.ToBinary<IBinaryObject>(new BinarizableEntry
{
Val = x.Value.Deserialize<BinarizableEntry>().Val + 1
})));
}
}
/// <summary>
/// Test serializable receiver.
/// </summary>
[Serializable]
private class StreamReceiverSerializable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test entry processor.
/// </summary>
[Serializable]
private class EntryProcessorSerializable : ICacheEntryProcessor<int, int, int, int>
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
}
/// <summary>
/// Test entry processor.
/// </summary>
private class EntryProcessorBinarizable : ICacheEntryProcessor<int, int, int, int>, IBinarizable
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
public int Val { get; set; }
}
/// <summary>
/// Container class.
/// </summary>
private class Container
{
public Container Inner;
}
private class CountingEntryProcessor : ICacheEntryProcessor<string, long, object, object>
{
public object Process(IMutableCacheEntry<string, long> e, object arg)
{
e.Value++;
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
using SortedDictionaryTests.SortedDictionary_SortedDictionary_CtorTests;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionaryTests
{
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType>
{
public int GetHashCode(KeyType key)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key1.GetHashCode();
}
public bool Equals(KeyType key1, KeyType key2)
{
return key1.Equals(key2);
}
}
namespace SortedDictionary_SortedDictionary_CtorTests
{
public class SortedDictionary_CtorTests
{
[Fact]
public static void SortedDictionary_DefaultCtorTest()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
SimpleRef<int>[] ints = new SimpleRef<int>[] { new SimpleRef<int>(1), new SimpleRef<int>(2), new SimpleRef<int>(3) };
SimpleRef<String>[] strings = new SimpleRef<String>[] { new SimpleRef<String>("1"), new SimpleRef<String>("2"), new SimpleRef<String>("3") };
//Scenario 1: Vanilla - Create a SortedDictionary and check that default properties are set
driver1.TestVanilla();
driver2.TestVanilla();
driver3.TestVanilla();
driver4.TestVanilla();
//Scenario 2: Vanilla - Make sure that we can add key-value pairs to this
driver1.TestCanAdd(ints, strings);
driver2.TestCanAdd(strings, ints);
driver3.TestCanAdd(ints, ints);
driver4.TestCanAdd(strings, strings);
}
[Fact]
public static void SortedDictionary_IDictionaryCtorTest()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
int count;
SimpleRef<int>[] ints;
SimpleRef<String>[] strings;
SortedDictionary<SimpleRef<int>, SimpleRef<String>> dic1;
SortedDictionary<SimpleRef<String>, SimpleRef<int>> dic2;
SortedDictionary<SimpleRef<int>, SimpleRef<int>> dic3;
SortedDictionary<SimpleRef<String>, SimpleRef<String>> dic4;
//Scenario 1: Vanilla - Create SortedDictionary using another SortedDictionary with 10 key-values and check
count = 10;
ints = GetSimpleInts(count);
strings = GetSimpleStrings(count);
dic1 = FillValues(ints, strings);
dic2 = FillValues(strings, ints);
dic3 = FillValues(ints, ints);
dic4 = FillValues(strings, strings);
driver1.TestVanillaIDictionary(dic1);
driver2.TestVanillaIDictionary(dic2);
driver3.TestVanillaIDictionary(dic3);
driver4.TestVanillaIDictionary(dic4);
//Scenario 2: SortedDictionary with 100 entries
count = 100;
ints = GetSimpleInts(count);
strings = GetSimpleStrings(count);
dic1 = FillValues(ints, strings);
dic2 = FillValues(strings, ints);
dic3 = FillValues(ints, ints);
dic4 = FillValues(strings, strings);
driver1.TestVanillaIDictionary(dic1);
driver2.TestVanillaIDictionary(dic2);
driver3.TestVanillaIDictionary(dic3);
driver4.TestVanillaIDictionary(dic4);
//Scenario 3: Implement our own type that implements IDictionary<KeyType, ValueType> and test
TestSortedDictionary<SimpleRef<int>, SimpleRef<String>> myDic1 = new TestSortedDictionary<SimpleRef<int>, SimpleRef<String>>(ints, strings);
TestSortedDictionary<SimpleRef<String>, SimpleRef<int>> myDic2 = new TestSortedDictionary<SimpleRef<String>, SimpleRef<int>>(strings, ints);
TestSortedDictionary<SimpleRef<int>, SimpleRef<int>> myDic3 = new TestSortedDictionary<SimpleRef<int>, SimpleRef<int>>(ints, ints);
TestSortedDictionary<SimpleRef<String>, SimpleRef<String>> myDic4 = new TestSortedDictionary<SimpleRef<String>, SimpleRef<String>>(strings, strings);
driver1.TestVanillaIDictionary(myDic1);
driver2.TestVanillaIDictionary(myDic2);
driver3.TestVanillaIDictionary(myDic3);
driver4.TestVanillaIDictionary(myDic4);
driver1.TestVanillaIDictionary(new SortedDictionary<SimpleRef<int>, SimpleRef<String>>());
driver2.TestVanillaIDictionary(new SortedDictionary<SimpleRef<String>, SimpleRef<int>>());
driver3.TestVanillaIDictionary(new SortedDictionary<SimpleRef<int>, SimpleRef<int>>());
driver4.TestVanillaIDictionary(new SortedDictionary<SimpleRef<String>, SimpleRef<String>>());
}
[Fact]
public static void SortedDictionary_IDictionaryIKeyComparerCtorTest()
{
Driver<String, String> driver = new Driver<String, String>();
int count;
SimpleRef<int>[] simpleInts;
SimpleRef<String>[] simpleStrings;
String[] strings;
SortedDictionary<String, String> dic1;
count = 10;
strings = new String[count];
for (int i = 0; i < count; i++)
strings[i] = i.ToString();
simpleInts = GetSimpleInts(count);
simpleStrings = GetSimpleStrings(count);
dic1 = FillValues(strings, strings);
// Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver.TestEnumIDictionary_IKeyComparer(dic1);
// Scenario 2: Implement our own IKeyComparer and check
driver.IkeyComparerOwnImplementation(dic1);
//Scenario 3: ensure that SortedDictionary items from the passed IDictionary object use the interface IKeyComparer's Equals and GetHashCode APIs.
//Ex. Pass the case invariant IKeyComparer and check
//@TODO!!!
//Scenario 4: Contradictory values and check: ex. IDictionary is case insensitive but IKeyComparer is not
}
[Fact]
public static void SortedDictionary_IKeyComparerCtorTest()
{
Driver<String, String> driver1 = new Driver<String, String>();
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver1.TestEnumIKeyComparer();
//Scenario 2: Parm validation: null
// If comparer is null, this constructor uses the default generic equality comparer, Comparer<T>.Default.
driver1.TestParmIKeyComparer();
//Scenario 3: Implement our own IKeyComparer and check
driver1.IkeyComparerOwnImplementation(null);
}
[Fact]
public static void SortedDictionary_IDictionaryIKeyComparerCtorTest_Negative()
{
Driver<String, String> driver = new Driver<String, String>();
//Param validation: null
driver.TestParmIDictionaryIKeyComparer();
}
[Fact]
public static void SortedDictionary_IDictionaryCtorTest_Negative()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
//Scenario 4: Parm validation: null, empty SortedDictionary
driver1.TestParmIDictionary(null);
driver2.TestParmIDictionary(null);
driver3.TestParmIDictionary(null);
driver4.TestParmIDictionary(null);
}
private static SortedDictionary<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] ints = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
ints[i] = new SimpleRef<int>(i);
return ints;
}
private static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] strings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
strings[i] = new SimpleRef<String>(i.ToString());
return strings;
}
}
/// Helper class
public class Driver<KeyType, ValueType>
{
private CultureInfo _english = new CultureInfo("en");
private CultureInfo _german = new CultureInfo("de");
private CultureInfo _danish = new CultureInfo("da");
private CultureInfo _turkish = new CultureInfo("tr");
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestVanilla()
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_001! Comparer differ"
Assert.Equal(_dic.Count, 0); //"Err_002! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_003! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_004! Key count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_005! Values count is different"
}
public void TestVanillaIDictionary(IDictionary<KeyType, ValueType> SortedDictionary)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(SortedDictionary);
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_006! Comparer differ"
Assert.Equal(_dic.Count, SortedDictionary.Count); //"Err_007! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_008! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, SortedDictionary.Count); //"Err_009! Key count is different"
Assert.Equal(_dic.Values.Count, SortedDictionary.Count); //"Err_010! Values count is different"
}
public void TestParmIDictionary(IDictionary<KeyType, ValueType> SortedDictionary)
{
Assert.Throws<ArgumentNullException>(() => new SortedDictionary<KeyType, ValueType>(SortedDictionary)); //"Err_011! wrong exception thrown."
}
public void TestCanAdd(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
Assert.Equal(_dic.Count, keys.Length); //"Err_012! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_013! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, keys.Length); //"Err_014! Keys count is different"
Assert.Equal(_dic.Values.Count, values.Length); //"Err_015! values count is different"
}
public void TestEnumIDictionary_IKeyComparer(IDictionary<String, String> idic)
{
SortedDictionary<String, String> _dic;
IComparer<String> comparer;
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedDictionary<String, String>(predefinedComparer);
Assert.Equal(_dic.Comparer, predefinedComparer); //"Err_016! Comparers differ"
Assert.Equal(_dic.Count, 0); //"Err_017! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_018! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_019! Count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_020! Count is different"
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_021! Comparer is different"
_dic.Add(strAE, value);
Assert.False(_dic.ContainsKey(strUC4)); //"Err_022! Expected that _dic.ContainsKey(strUC4) would return false"
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_025! Comparer is different"
_dic.Add(straA, value);
Assert.True(_dic.ContainsKey(strAa)); //"Err_026! Expected that _dic.ContainsKey(strAa) would return true"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_027! Comparer is different"
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_028! Expected that _dic.ContainsKey(strAa) would return false"
//Ordinal
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_029! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_030! Expected that _dic.ContainsKey(strbb) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_031! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_032! Expected that _dic.ContainsKey(strbb) would return false"
}
public void TestEnumIKeyComparer()
{
SortedDictionary<String, String> _dic;
IComparer<String> comparer;
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedDictionary<String, String>(predefinedComparer);
Assert.Equal(_dic.Comparer, predefinedComparer); //"Err_033! Comparer is different"
Assert.Equal(_dic.Count, 0); //"Err_034! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_035! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_036! Count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_037! Count is different"
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_038! Comparer is different"
_dic.Add(strAE, value);
Assert.False(_dic.ContainsKey(strUC4)); //"Err_039! Expected that _dic.ContainsKey(strUC4) would return false"
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_040! Comparer is different"
_dic.Add(straA, value);
Assert.True(_dic.ContainsKey(strAa)); //"Err_041! Expected that _dic.ContainsKey(strAa) would return true"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_042! Comparer is different"
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_043! Expected that _dic.ContainsKey(strAa) would return false"
//Ordinal
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_044! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_045! Expected that _dic.ContainsKey(strbb) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_046! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_047! Expected that _dic.ContainsKey(strbb) would return false"
}
public void TestParmIDictionaryIKeyComparer()
{
//passing null will revert to the default comparison mechanism
SortedDictionary<String, String> _dic;
IComparer<String> comparer = null;
SortedDictionary<String, String> dic1 = new SortedDictionary<String, String>();
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedDictionary<String, String>(dic1, comparer);
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_048! Expected that _dic.ContainsKey(strAa) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedDictionary<String, String>(dic1, comparer);
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_049! Expected that _dic.ContainsKey(strAa) would return false"
comparer = StringComparer.CurrentCulture;
dic1 = null;
CultureInfo.DefaultThreadCurrentCulture = _english;
Assert.Throws<ArgumentNullException>(() => new SortedDictionary<String, String>(dic1, comparer)); //"Err_050! wrong exception thrown."
}
public void TestParmIKeyComparer()
{
IComparer<KeyType> comparer = null;
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(comparer);
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_051! Comparer differ"
Assert.Equal(_dic.Count, 0); //"Err_052! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_053! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_054! Key count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_055! Values count is different"
}
public void IkeyComparerOwnImplementation(IDictionary<String, String> idic)
{
//This just ensures that we can call our own implementation
SortedDictionary<String, String> _dic;
IComparer<String> comparer = new MyOwnIKeyImplementation<String>();
CultureInfo.DefaultThreadCurrentCulture = _english;
if (idic == null)
{
_dic = new SortedDictionary<String, String>(comparer);
}
else
{
_dic = new SortedDictionary<String, String>(idic, comparer);
}
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_056! Expected that _dic.ContainsKey(strAa) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
if (idic == null)
{
_dic = new SortedDictionary<String, String>(comparer);
}
else
{
_dic = new SortedDictionary<String, String>(idic, comparer);
}
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_057! Expected that _dic.ContainsKey(strAa) would return false"
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using TestExtensions;
using Xunit;
namespace UnitTests.Serialization
{
/// <summary>
/// Summary description for SerializationTests
/// </summary>
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class SerializationTestsDifferentTypes
{
private readonly TestEnvironmentFixture fixture;
public SerializationTestsDifferentTypes(TestEnvironmentFixture fixture)
{
this.fixture = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_DateTime()
{
// Local Kind
DateTime inputLocal = DateTime.Now;
DateTime outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal.ToString(CultureInfo.InvariantCulture), outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.Kind, outputLocal.Kind);
// UTC Kind
DateTime inputUtc = DateTime.UtcNow;
DateTime outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc.ToString(CultureInfo.InvariantCulture), outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.Kind, outputUtc.Kind);
// Unspecified Kind
DateTime inputUnspecified = new DateTime(0x08d27e2c0cc7dfb9);
DateTime outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified.ToString(CultureInfo.InvariantCulture), outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.Kind, outputUnspecified.Kind);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_DateTimeOffset()
{
// Local Kind
DateTime inputLocalDateTime = DateTime.Now;
DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime);
DateTimeOffset outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal, outputLocal);
Assert.Equal(
inputLocal.ToString(CultureInfo.InvariantCulture),
outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind);
// UTC Kind
DateTime inputUtcDateTime = DateTime.UtcNow;
DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime);
DateTimeOffset outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc, outputUtc);
Assert.Equal(
inputUtc.ToString(CultureInfo.InvariantCulture),
outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind);
// Unspecified Kind
DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9);
DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime);
DateTimeOffset outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified, outputUnspecified);
Assert.Equal(
inputUnspecified.ToString(CultureInfo.InvariantCulture),
outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind);
}
[Serializable]
private class TestTypeA
{
public ICollection<TestTypeA> Collection { get; set; }
}
[Serializer(typeof(TestTypeA))]
internal class TestTypeASerialization
{
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
TestTypeA input = (TestTypeA)original;
TestTypeA result = new TestTypeA();
context.RecordCopy(original, result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeepCopyInner(input.Collection, context);
return result;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
TestTypeA input = (TestTypeA)untypedInput;
SerializationManager.SerializeInner(input.Collection, context, typeof(ICollection<TestTypeA>));
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
TestTypeA result = new TestTypeA();
context.RecordObject(result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeserializeInner(typeof(ICollection<TestTypeA>), context);
return result;
}
}
#if !NETSTANDARD_TODO
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_RecursiveSerialization()
{
TestTypeA input = new TestTypeA();
input.Collection = new HashSet<TestTypeA>();
input.Collection.Add(input);
TestTypeA output1 = Orleans.TestingHost.Utils.TestingUtils.RoundTripDotNetSerializer(input, this.fixture.GrainFactory, this.fixture.SerializationManager);
TestTypeA output2 = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
}
#endif
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_CultureInfo()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
foreach (var cultureInfo in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(cultureInfo);
Assert.Equal(cultureInfo, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_CultureInfoList()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
Assert.True(input.SequenceEqual(output));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple()
{
var input = new List<ValueTuple<int>> { ValueTuple.Create(1), ValueTuple.Create(100) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple2()
{
var input = new List<ValueTuple<int, int>> { ValueTuple.Create(1, 2), ValueTuple.Create(100, 200) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple3()
{
var input = new List<ValueTuple<int, int, int>>
{
ValueTuple.Create(1, 2, 3),
ValueTuple.Create(100, 200, 300)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple4()
{
var input = new List<ValueTuple<int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4),
ValueTuple.Create(100, 200, 300, 400)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple5()
{
var input = new List<ValueTuple<int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5),
ValueTuple.Create(100, 200, 300, 400, 500)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple6()
{
var input = new List<ValueTuple<int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6),
ValueTuple.Create(100, 200, 300, 400, 500, 600)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple7()
{
var input = new List<ValueTuple<int, int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6, 7),
ValueTuple.Create(100, 200, 300, 400, 500, 600, 700)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple8()
{
var valueTuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
#if CLR2COMPATIBILITY
using Microsoft.Build.Shared.Concurrent;
#else
using System.Collections.Concurrent;
#endif
using System.IO;
using System.IO.Pipes;
using System.Threading;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
#if FEATURE_SECURITY_PERMISSIONS || FEATURE_PIPE_SECURITY
using System.Security.AccessControl;
#endif
#if FEATURE_PIPE_SECURITY && FEATURE_NAMED_PIPE_SECURITY_CONSTRUCTOR
using System.Security.Principal;
#endif
#if !FEATURE_APM
using System.Threading.Tasks;
#endif
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// This is an implementation of INodeEndpoint for the out-of-proc nodes. It acts only as a client.
/// </summary>
internal abstract class NodeEndpointOutOfProcBase : INodeEndpoint
{
#region Private Data
#if NETCOREAPP2_1 || MONO
/// <summary>
/// The amount of time to wait for the client to connect to the host.
/// </summary>
private const int ClientConnectTimeout = 60000;
#endif // NETCOREAPP2_1 || MONO
/// <summary>
/// The size of the buffers to use for named pipes
/// </summary>
private const int PipeBufferSize = 131072;
/// <summary>
/// Flag indicating if we should debug communications or not.
/// </summary>
private bool _debugCommunications = false;
/// <summary>
/// The current communication status of the node.
/// </summary>
private LinkStatus _status;
/// <summary>
/// The pipe client used by the nodes.
/// </summary>
private NamedPipeServerStream _pipeServer;
// The following private data fields are used only when the endpoint is in ASYNCHRONOUS mode.
/// <summary>
/// Object used as a lock source for the async data
/// </summary>
private object _asyncDataMonitor;
/// <summary>
/// Set when a packet is available in the packet queue
/// </summary>
private AutoResetEvent _packetAvailable;
/// <summary>
/// Set when the asynchronous packet pump should terminate
/// </summary>
private AutoResetEvent _terminatePacketPump;
/// <summary>
/// The thread which runs the asynchronous packet pump
/// </summary>
private Thread _packetPump;
/// <summary>
/// The factory used to create and route packets.
/// </summary>
private INodePacketFactory _packetFactory;
/// <summary>
/// The asynchronous packet queue.
/// </summary>
/// <remarks>
/// Operations on this queue must be synchronized since it is accessible by multiple threads.
/// Use a lock on the packetQueue itself.
/// </remarks>
private ConcurrentQueue<INodePacket> _packetQueue;
/// <summary>
/// Per-node shared read buffer.
/// </summary>
private SharedReadBuffer _sharedReadBuffer;
/// <summary>
/// A way to cache a byte array when writing out packets
/// </summary>
private MemoryStream _packetStream;
/// <summary>
/// A binary writer to help write into <see cref="_packetStream"/>
/// </summary>
private BinaryWriter _binaryWriter;
#endregion
#region INodeEndpoint Events
/// <summary>
/// Raised when the link status has changed.
/// </summary>
public event LinkStatusChangedDelegate OnLinkStatusChanged;
#endregion
#region INodeEndpoint Properties
/// <summary>
/// Returns the link status of this node.
/// </summary>
public LinkStatus LinkStatus
{
get { return _status; }
}
#endregion
#region Properties
#endregion
#region INodeEndpoint Methods
/// <summary>
/// Causes this endpoint to wait for the remote endpoint to connect
/// </summary>
/// <param name="factory">The factory used to create packets.</param>
public void Listen(INodePacketFactory factory)
{
ErrorUtilities.VerifyThrow(_status == LinkStatus.Inactive, "Link not inactive. Status is {0}", _status);
ErrorUtilities.VerifyThrowArgumentNull(factory, nameof(factory));
_packetFactory = factory;
InitializeAsyncPacketThread();
}
/// <summary>
/// Causes this node to connect to the matched endpoint.
/// </summary>
/// <param name="factory">The factory used to create packets.</param>
public void Connect(INodePacketFactory factory)
{
ErrorUtilities.ThrowInternalError("Connect() not valid on the out of proc endpoint.");
}
/// <summary>
/// Shuts down the link
/// </summary>
public void Disconnect()
{
InternalDisconnect();
}
/// <summary>
/// Sends data to the peer endpoint.
/// </summary>
/// <param name="packet">The packet to send.</param>
public void SendData(INodePacket packet)
{
// PERF: Set up a priority system so logging packets are sent only when all other packet types have been sent.
if (_status == LinkStatus.Active)
{
EnqueuePacket(packet);
}
}
#endregion
#region Construction
/// <summary>
/// Instantiates an endpoint to act as a client
/// </summary>
/// <param name="pipeName">The name of the pipe to which we should connect.</param>
internal void InternalConstruct(string pipeName)
{
ErrorUtilities.VerifyThrowArgumentLength(pipeName, nameof(pipeName));
_debugCommunications = (Environment.GetEnvironmentVariable("MSBUILDDEBUGCOMM") == "1");
_status = LinkStatus.Inactive;
_asyncDataMonitor = new object();
_sharedReadBuffer = InterningBinaryReader.CreateSharedBuffer();
_packetStream = new MemoryStream();
_binaryWriter = new BinaryWriter(_packetStream);
#if FEATURE_PIPE_SECURITY && FEATURE_NAMED_PIPE_SECURITY_CONSTRUCTOR
if (!NativeMethodsShared.IsMono)
{
SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
PipeSecurity security = new PipeSecurity();
// Restrict access to just this account. We set the owner specifically here, and on the
// pipe client side they will check the owner against this one - they must have identical
// SIDs or the client will reject this server. This is used to avoid attacks where a
// hacked server creates a less restricted pipe in an attempt to lure us into using it and
// then sending build requests to the real pipe client (which is the MSBuild Build Manager.)
PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite, AccessControlType.Allow);
security.AddAccessRule(rule);
security.SetOwner(identifier);
_pipeServer = new NamedPipeServerStream
(
pipeName,
PipeDirection.InOut,
1, // Only allow one connection at a time.
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.WriteThrough,
PipeBufferSize, // Default input buffer
PipeBufferSize, // Default output buffer
security,
HandleInheritability.None
);
}
else
#endif
{
_pipeServer = new NamedPipeServerStream
(
pipeName,
PipeDirection.InOut,
1, // Only allow one connection at a time.
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.WriteThrough,
PipeBufferSize, // Default input buffer
PipeBufferSize // Default output buffer
);
}
}
#endregion
/// <summary>
/// Returns the host handshake for this node endpoint
/// </summary>
protected abstract Handshake GetHandshake();
/// <summary>
/// Updates the current link status if it has changed and notifies any registered delegates.
/// </summary>
/// <param name="newStatus">The status the node should now be in.</param>
protected void ChangeLinkStatus(LinkStatus newStatus)
{
ErrorUtilities.VerifyThrow(_status != newStatus, "Attempting to change status to existing status {0}.", _status);
CommunicationsUtilities.Trace("Changing link status from {0} to {1}", _status.ToString(), newStatus.ToString());
_status = newStatus;
RaiseLinkStatusChanged(_status);
}
/// <summary>
/// Invokes the OnLinkStatusChanged event in a thread-safe manner.
/// </summary>
/// <param name="newStatus">The new status of the endpoint link.</param>
private void RaiseLinkStatusChanged(LinkStatus newStatus)
{
OnLinkStatusChanged?.Invoke(this, newStatus);
}
#region Private Methods
/// <summary>
/// This does the actual work of changing the status and shutting down any threads we may have for
/// disconnection.
/// </summary>
private void InternalDisconnect()
{
ErrorUtilities.VerifyThrow(_packetPump.ManagedThreadId != Thread.CurrentThread.ManagedThreadId, "Can't join on the same thread.");
_terminatePacketPump.Set();
_packetPump.Join();
#if CLR2COMPATIBILITY
_terminatePacketPump.Close();
#else
_terminatePacketPump.Dispose();
#endif
_pipeServer.Dispose();
_packetPump = null;
ChangeLinkStatus(LinkStatus.Inactive);
}
#region Asynchronous Mode Methods
/// <summary>
/// Adds a packet to the packet queue when asynchronous mode is enabled.
/// </summary>
/// <param name="packet">The packet to be transmitted.</param>
private void EnqueuePacket(INodePacket packet)
{
ErrorUtilities.VerifyThrowArgumentNull(packet, nameof(packet));
ErrorUtilities.VerifyThrow(_packetQueue != null, "packetQueue is null");
ErrorUtilities.VerifyThrow(_packetAvailable != null, "packetAvailable is null");
_packetQueue.Enqueue(packet);
_packetAvailable.Set();
}
/// <summary>
/// Initializes the packet pump thread and the supporting events as well as the packet queue.
/// </summary>
private void InitializeAsyncPacketThread()
{
lock (_asyncDataMonitor)
{
_packetPump = new Thread(PacketPumpProc);
_packetPump.IsBackground = true;
_packetPump.Name = "OutOfProc Endpoint Packet Pump";
_packetAvailable = new AutoResetEvent(false);
_terminatePacketPump = new AutoResetEvent(false);
_packetQueue = new ConcurrentQueue<INodePacket>();
_packetPump.Start();
}
}
/// <summary>
/// This method handles the asynchronous message pump. It waits for messages to show up on the queue
/// and calls FireDataAvailable for each such packet. It will terminate when the terminate event is
/// set.
/// </summary>
private void PacketPumpProc()
{
NamedPipeServerStream localPipeServer = _pipeServer;
AutoResetEvent localPacketAvailable = _packetAvailable;
AutoResetEvent localTerminatePacketPump = _terminatePacketPump;
ConcurrentQueue<INodePacket> localPacketQueue = _packetQueue;
DateTime originalWaitStartTime = DateTime.UtcNow;
bool gotValidConnection = false;
while (!gotValidConnection)
{
gotValidConnection = true;
DateTime restartWaitTime = DateTime.UtcNow;
// We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
// to attach. This prevents each attempt from resetting the timer.
TimeSpan usedWaitTime = restartWaitTime - originalWaitStartTime;
int waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);
try
{
// Wait for a connection
#if FEATURE_APM
IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
Task connectionTask = localPipeServer.WaitForConnectionAsync();
CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
if (!connected)
{
CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us. Exiting comm thread.");
ChangeLinkStatus(LinkStatus.ConnectionFailed);
return;
}
CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
localPipeServer.EndWaitForConnection(resultForConnection);
#endif
// The handshake protocol is a series of int exchanges. The host sends us a each component, and we
// verify it. Afterwards, the host sends an "End of Handshake" signal, to which we respond in kind.
// Once the handshake is complete, both sides can be assured the other is ready to accept data.
Handshake handshake = GetHandshake();
try
{
int[] handshakeComponents = handshake.RetrieveHandshakeComponents();
for (int i = 0; i < handshakeComponents.Length; i++)
{
int handshakePart = _pipeServer.ReadIntForHandshake(i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */
#if NETCOREAPP2_1 || MONO
, ClientConnectTimeout /* wait a long time for the handshake from this side */
#endif
);
if (handshakePart != handshakeComponents[i])
{
CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshakePart, handshakeComponents[i]);
_pipeServer.WriteIntForHandshake(i + 1);
gotValidConnection = false;
break;
}
}
if (gotValidConnection)
{
// To ensure that our handshake and theirs have the same number of bytes, receive and send a magic number indicating EOS.
#if NETCOREAPP2_1 || MONO
_pipeServer.ReadEndOfHandshakeSignal(false, ClientConnectTimeout); /* wait a long time for the handshake from this side */
#else
_pipeServer.ReadEndOfHandshakeSignal(false);
#endif
CommunicationsUtilities.Trace("Successfully connected to parent.");
_pipeServer.WriteEndOfHandshakeSignal();
#if FEATURE_SECURITY_PERMISSIONS
// We will only talk to a host that was started by the same user as us. Even though the pipe access is set to only allow this user, we want to ensure they
// haven't attempted to change those permissions out from under us. This ensures that the only way they can truly gain access is to be impersonating the
// user we were started by.
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsIdentity clientIdentity = null;
localPipeServer.RunAsClient(delegate () { clientIdentity = WindowsIdentity.GetCurrent(true); });
if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
{
CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
gotValidConnection = false;
continue;
}
#endif
}
}
catch (IOException e)
{
// We will get here when:
// 1. The host (OOP main node) connects to us, it immediately checks for user privileges
// and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
// 2. The host is too old sending us bits we automatically reject in the handshake
// 3. We expected to read the EndOfHandshake signal, but we received something else
CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);
gotValidConnection = false;
}
catch (InvalidOperationException)
{
gotValidConnection = false;
}
if (!gotValidConnection)
{
if (localPipeServer.IsConnected)
{
localPipeServer.Disconnect();
}
continue;
}
ChangeLinkStatus(LinkStatus.Active);
}
catch (Exception e)
{
if (ExceptionHandling.IsCriticalException(e))
{
throw;
}
CommunicationsUtilities.Trace("Client connection failed. Exiting comm thread. {0}", e);
if (localPipeServer.IsConnected)
{
localPipeServer.Disconnect();
}
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
return;
}
}
RunReadLoop(
new BufferedReadStream(_pipeServer),
_pipeServer,
localPacketQueue, localPacketAvailable, localTerminatePacketPump);
CommunicationsUtilities.Trace("Ending read loop");
try
{
if (localPipeServer.IsConnected)
{
#if NETCOREAPP // OperatingSystem.IsWindows() is new in .NET 5.0
if (OperatingSystem.IsWindows())
#endif
{
localPipeServer.WaitForPipeDrain();
}
localPipeServer.Disconnect();
}
}
catch (Exception)
{
// We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
}
}
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe,
ConcurrentQueue<INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump)
{
// Ordering of the wait handles is important. The first signalled wait handle in the array
// will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the
// terminate event triggered so that we cannot get into a situation where packets are being
// spammed to the endpoint and it never gets an opportunity to shutdown.
CommunicationsUtilities.Trace("Entering read loop.");
byte[] headerByte = new byte[5];
#if FEATURE_APM
IAsyncResult result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
Task<int> readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
bool exitLoop = false;
do
{
// Ordering is important. We want packetAvailable to supercede terminate otherwise we will not properly wait for all
// packets to be sent by other threads which are shutting down, such as the logging thread.
WaitHandle[] handles = new WaitHandle[] {
#if FEATURE_APM
result.AsyncWaitHandle,
#else
((IAsyncResult)readTask).AsyncWaitHandle,
#endif
localPacketAvailable, localTerminatePacketPump };
int waitId = WaitHandle.WaitAny(handles);
switch (waitId)
{
case 0:
{
int bytesRead = 0;
try
{
#if FEATURE_APM
bytesRead = localReadPipe.EndRead(result);
#else
bytesRead = readTask.Result;
#endif
}
catch (Exception e)
{
// Lost communications. Abort (but allow node reuse)
CommunicationsUtilities.Trace("Exception reading from server. {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Inactive);
exitLoop = true;
break;
}
if (bytesRead != headerByte.Length)
{
// Incomplete read. Abort.
if (bytesRead == 0)
{
CommunicationsUtilities.Trace("Parent disconnected abruptly");
}
else
{
CommunicationsUtilities.Trace("Incomplete header read from server. {0} of {1} bytes read", bytesRead, headerByte.Length);
}
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
NodePacketType packetType = (NodePacketType)Enum.ToObject(typeof(NodePacketType), headerByte[0]);
try
{
_packetFactory.DeserializeAndRoutePacket(0, packetType, BinaryTranslator.GetReadTranslator(localReadPipe, _sharedReadBuffer));
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while deserializing packet {0}: {1}", packetType, e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
#if FEATURE_APM
result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
}
break;
case 1:
case 2:
try
{
// Write out all the queued packets.
INodePacket packet;
while (localPacketQueue.TryDequeue(out packet))
{
var packetStream = _packetStream;
packetStream.SetLength(0);
ITranslator writeTranslator = BinaryTranslator.GetWriteTranslator(packetStream);
packetStream.WriteByte((byte)packet.Type);
// Pad for packet length
_binaryWriter.Write(0);
// Reset the position in the write buffer.
packet.Translate(writeTranslator);
int packetStreamLength = (int)packetStream.Position;
// Now write in the actual packet length
packetStream.Position = 1;
_binaryWriter.Write(packetStreamLength - 5);
localWritePipe.Write(packetStream.GetBuffer(), 0, packetStreamLength);
}
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while serializing packets: {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
if (waitId == 2)
{
CommunicationsUtilities.Trace("Disconnecting voluntarily");
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
}
break;
default:
ErrorUtilities.ThrowInternalError("waitId {0} out of range.", waitId);
break;
}
}
while (!exitLoop);
}
#endregion
#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.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
namespace System.IO
{
internal sealed class WinRTFileStream : FileStreamBase
{
private readonly FileAccess _access;
private bool _disposed;
private StorageFile _file;
private readonly Stream _innerStream;
private readonly FileOptions _options;
private static readonly SafeFileHandle s_invalidHandle = new SafeFileHandle(IntPtr.Zero, false);
internal WinRTFileStream(Stream innerStream, StorageFile file, FileAccess access, FileOptions options, FileStream parent)
: base(parent)
{
Debug.Assert(innerStream != null);
Debug.Assert(file != null);
this._access = access;
this._disposed = false;
this._file = file;
this._innerStream = innerStream;
this._options = options;
}
~WinRTFileStream()
{
Dispose(false);
}
#region FileStream members
public override bool IsAsync { get { return true; } }
public override string Name { get { return _file.Name; } }
public override Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { return s_invalidHandle; } }
public override void Flush(bool flushToDisk)
{
// WinRT streams are not buffered, however the WinRT stream will be wrapped in a BufferedStream
// Flush & FlushAsync will flush the internal managed buffer of the BufferedStream wrapper
// The WinRT stream only exposes FlushAsync which flushes to disk.
// The managed Stream adapter does nothing for Flush() and forwards to WinRT for FlushAsync (flushing to disk).
if (flushToDisk)
{
// FlushAsync() will do the write to disk when it hits the WinRT->NetFx adapter
Task flushTask = _innerStream.FlushAsync();
flushTask.Wait();
}
else
{
// Flush doesn't write to disk
_innerStream.Flush();
}
}
#endregion
#region Stream members
#region Properties
public override bool CanRead
{
// WinRT doesn't support write-only streams, override what the stream tells us
// with what was passed in when creating it.
get { return _innerStream.CanRead && (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek
{
get { return _innerStream.CanSeek; }
}
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
public override long Length
{
get { return _innerStream.Length; }
}
public override long Position
{
get { return _innerStream.Position; }
set { _innerStream.Position = value; }
}
public override int ReadTimeout
{
get { return _innerStream.ReadTimeout; }
set { _innerStream.ReadTimeout = value; }
}
public override bool CanTimeout
{
get { return _innerStream.CanTimeout; }
}
public override int WriteTimeout
{
get { return _innerStream.WriteTimeout; }
set { _innerStream.WriteTimeout = value; }
}
#endregion Properties
#region Methods
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
return _innerStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
_innerStream.Dispose();
if ((_options & FileOptions.DeleteOnClose) != 0 && _file != null)
{
// WinRT doesn't directly support DeleteOnClose but we can mimick it
// There are a few reasons that this will fail
// 1) the file may not allow delete permissions for the current user
// 2) the storage file RCW may have already been disconnected
try
{
_file.DeleteAsync().AsTask().Wait();
}
catch { }
}
_disposed = true;
_file = null;
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{
_parent.Flush(false);
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _innerStream.FlushAsync(cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!_disposed && !CanRead)
throw Error.GetReadNotSupported();
return _innerStream.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!_disposed && !CanRead)
throw Error.GetReadNotSupported();
return _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int ReadByte()
{
if (!_disposed && !CanRead)
throw Error.GetReadNotSupported();
return _innerStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin && offset < 0)
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_NEGATIVE_SEEK);
return _innerStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_innerStream.SetLength(value);
// WinRT ignores all errors when setting length, check after setting
if (_innerStream.Length < value)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_FileLengthTooBig);
}
else if (_innerStream.Length != value)
{
throw new ArgumentException("value");
}
// WinRT doesn't update the position when truncating a file
if (value < _innerStream.Position)
_innerStream.Position = value;
}
public override string ToString()
{
return _innerStream.ToString();
}
public override void Write(byte[] buffer, int offset, int count)
{
_innerStream.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void WriteByte(byte value)
{
_innerStream.WriteByte(value);
}
#endregion Methods
#endregion Stream members
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The specification for a pool.
/// </summary>
public partial class PoolSpecification : ITransportObjectProvider<Models.PoolSpecification>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<IList<MountConfiguration>> MountConfigurationProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<int?> TaskSlotsPerNodeProperty;
public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor<IList<MountConfiguration>>(nameof(MountConfiguration), BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor<int?>(nameof(TaskSlotsPerNode), BindingAccess.Read | BindingAccess.Write);
this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.PoolSpecification protocolObject) : base(BindingState.Bound)
{
this.ApplicationLicensesProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),
nameof(ApplicationLicenses),
BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
nameof(AutoScaleEnabled),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
nameof(AutoScaleEvaluationInterval),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
nameof(AutoScaleFormula),
BindingAccess.Read | BindingAccess.Write);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
nameof(CertificateReferences),
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o)),
nameof(CloudServiceConfiguration),
BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
nameof(InterComputeNodeCommunicationEnabled),
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor(
Batch.MountConfiguration.ConvertFromProtocolCollectionAndFreeze(protocolObject.MountConfiguration),
nameof(MountConfiguration),
BindingAccess.Read);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
nameof(NetworkConfiguration),
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
nameof(ResizeTimeout),
BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
nameof(StartTask),
BindingAccess.Read | BindingAccess.Write);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicatedNodes,
nameof(TargetDedicatedComputeNodes),
BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetLowPriorityNodes,
nameof(TargetLowPriorityComputeNodes),
BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o)),
nameof(TaskSchedulingPolicy),
BindingAccess.Read | BindingAccess.Write);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor(
protocolObject.TaskSlotsPerNode,
nameof(TaskSlotsPerNode),
BindingAccess.Read | BindingAccess.Write);
this.UserAccountsProperty = this.CreatePropertyAccessor(
UserAccount.ConvertFromProtocolCollection(protocolObject.UserAccounts),
nameof(UserAccounts),
BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o)),
nameof(VirtualMachineConfiguration),
BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
nameof(VirtualMachineSize),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PoolSpecification"/> class.
/// </summary>
public PoolSpecification()
{
this.propertyContainer = new PropertyContainer();
}
internal PoolSpecification(Models.PoolSpecification protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region PoolSpecification
/// <summary>
/// Gets or sets the list of application licenses the Batch service will make available on each compute node in the
/// pool.
/// </summary>
/// <remarks>
/// The list of application licenses must be a subset of available Batch service application licenses.
/// </remarks>
public IList<string> ApplicationLicenses
{
get { return this.propertyContainer.ApplicationLicensesProperty.Value; }
set
{
this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets a list of application package references to be installed on each compute node in the pool.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust over time.
/// </summary>
/// <remarks>
/// <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/>
/// property is required.</para> <para>If true, the <see cref="AutoScaleFormula"/> property is required. The pool
/// automatically resizes according to the formula.</para> <para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="PoolSpecification"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
/// <remarks>
/// This property is mutually exclusive with <see cref="VirtualMachineConfiguration"/>.
/// </remarks>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name for the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets a list of file systems to mount on each node in the pool.
/// </summary>
/// <remarks>
/// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse.
/// </remarks>
public IList<MountConfiguration> MountConfiguration
{
get { return this.propertyContainer.MountConfigurationProperty.Value; }
set
{
this.propertyContainer.MountConfigurationProperty.Value = ConcurrentChangeTrackedModifiableList<MountConfiguration>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
/// <remarks>
/// <para>This timeout applies only to manual scaling; it has no effect when <see cref="AutoScaleEnabled"/> is set
/// to true.</para><para>The default value is 15 minutes. The minimum value is 5 minutes.</para>
/// </remarks>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of dedicated compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property
/// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false.
/// If not specified, the default is 0.
/// </remarks>
public int? TargetDedicatedComputeNodes
{
get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; }
set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of low-priority compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/>
/// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default
/// is 0.
/// </remarks>
public int? TargetLowPriorityComputeNodes
{
get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; }
set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets or sets the number of task slots that can be used to run concurrent tasks on a single compute node in the
/// pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the <see cref="VirtualMachineSize"/>
/// of the pool or 256.
/// </remarks>
public int? TaskSlotsPerNode
{
get { return this.propertyContainer.TaskSlotsPerNodeProperty.Value; }
set { this.propertyContainer.TaskSlotsPerNodeProperty.Value = value; }
}
/// <summary>
/// Gets or sets the list of user accounts to be created on each node in the pool.
/// </summary>
public IList<UserAccount> UserAccounts
{
get { return this.propertyContainer.UserAccountsProperty.Value; }
set
{
this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
/// <remarks>
/// This property is mutually exclusive with <see cref="CloudServiceConfiguration"/>.
/// </remarks>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes
/// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // PoolSpecification
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolSpecification ITransportObjectProvider<Models.PoolSpecification>.GetTransportObject()
{
Models.PoolSpecification result = new Models.PoolSpecification()
{
ApplicationLicenses = this.ApplicationLicenses,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
MountConfiguration = UtilitiesInternal.ConvertToProtocolCollection(this.MountConfiguration),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicatedNodes = this.TargetDedicatedComputeNodes,
TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
TaskSlotsPerNode = this.TaskSlotsPerNode,
UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TextBoxTests
{
[Fact]
public void Opening_Context_Menu_Does_not_Lose_Selection()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
ContextMenu = new TestContextMenu()
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot() { Child = sp };
target1.SelectionStart = 0;
target1.SelectionEnd = 3;
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
target2.Focus();
Assert.Equal("123", target1.SelectedText);
}
}
[Fact]
public void Opening_Context_Flyout_Does_not_Lose_Selection()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
ContextFlyout = new MenuFlyout
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Item 1" },
new MenuItem {Header = "Item 2" },
new MenuItem {Header = "Item 3" }
}
}
};
target1.ApplyTemplate();
var root = new TestRoot() { Child = target1 };
target1.SelectionStart = 0;
target1.SelectionEnd = 3;
target1.Focus();
Assert.True(target1.IsFocused);
target1.ContextFlyout.ShowAt(target1);
Assert.Equal("123", target1.SelectedText);
}
}
[Fact]
public void DefaultBindingMode_Should_Be_TwoWay()
{
Assert.Equal(
BindingMode.TwoWay,
TextBox.TextProperty.GetMetadata(typeof(TextBox)).DefaultBindingMode);
}
[Fact]
public void CaretIndex_Can_Moved_To_Position_After_The_End_Of_Text_With_Arrow_Key()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
target.CaretIndex = 3;
RaiseKeyEvent(target, Key.Right, 0);
Assert.Equal(4, target.CaretIndex);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(4, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Null_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate()
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(0, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_Z_Will_Not_Modify_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Typing_Beginning_With_0_Should_Not_Modify_Text_When_Bound_To_Int()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1();
var target = new TextBox
{
DataContext = source,
Template = CreateTemplate(),
};
target.ApplyTemplate();
target.Bind(TextBox.TextProperty, new Binding(nameof(Class1.Foo), BindingMode.TwoWay));
Assert.Equal("0", target.Text);
target.CaretIndex = 1;
target.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = "2",
});
Assert.Equal("02", target.Text);
}
}
[Fact]
public void Control_Backspace_Should_Remove_The_Word_Before_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 5
};
// (First| Second Third Fourth)
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Second Third Fourth", textBox.Text);
// ( Second |Third Fourth)
textBox.CaretIndex = 8;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Third Fourth", textBox.Text);
// ( Thi|rd Fourth)
textBox.CaretIndex = 4;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Fourth", textBox.Text);
// ( rd F[ou]rth)
textBox.SelectionStart = 5;
textBox.SelectionEnd = 7;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Frth", textBox.Text);
// ( |rd Frth)
textBox.CaretIndex = 1;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal("rd Frth", textBox.Text);
}
}
[Fact]
public void Control_Delete_Should_Remove_The_Word_After_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 19
};
// (First Second Third |Fourth)
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second Third ", textBox.Text);
// (First Second |Third )
textBox.CaretIndex = 13;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second ", textBox.Text);
// (First Sec|ond )
textBox.CaretIndex = 9;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Sec", textBox.Text);
// (Fi[rs]t Sec )
textBox.SelectionStart = 2;
textBox.SelectionEnd = 4;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
// (Fit Sec| )
textBox.Text += " ";
textBox.CaretIndex = 7;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
}
}
[Fact]
public void Setting_SelectionStart_To_SelectionEnd_Sets_CaretPosition_To_SelectionStart()
{
using (UnitTestApplication.Start(Services))
{
var textBox = new TextBox
{
Text = "0123456789"
};
textBox.SelectionStart = 2;
textBox.SelectionEnd = 2;
Assert.Equal(2, textBox.CaretIndex);
}
}
[Fact]
public void Setting_Text_Updates_CaretPosition()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Text = "Initial Text",
CaretIndex = 11
};
var invoked = false;
target.GetObservable(TextBox.TextProperty).Skip(1).Subscribe(_ =>
{
// Caret index should be set before Text changed notification, as we don't want
// to notify with an invalid CaretIndex.
Assert.Equal(7, target.CaretIndex);
invoked = true;
});
target.Text = "Changed";
Assert.True(invoked);
}
}
[Fact]
public void Press_Enter_Does_Not_Accept_Return()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = false,
Text = "1234"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Press_Enter_Add_Default_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal(Environment.NewLine, target.Text);
}
}
[Fact]
public void Press_Enter_Add_Custom_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true,
NewLine = "Test"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("Test", target.Text);
}
}
[Theory]
[InlineData(new object[] { false, TextWrapping.NoWrap, ScrollBarVisibility.Hidden })]
[InlineData(new object[] { false, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
[InlineData(new object[] { true, TextWrapping.NoWrap, ScrollBarVisibility.Auto })]
[InlineData(new object[] { true, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
public void Has_Correct_Horizontal_ScrollBar_Visibility(
bool acceptsReturn,
TextWrapping wrapping,
ScrollBarVisibility expected)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
AcceptsReturn = acceptsReturn,
TextWrapping = wrapping,
};
Assert.Equal(expected, ScrollViewer.GetHorizontalScrollBarVisibility(target));
}
}
[Fact]
public void SelectionEnd_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 0;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStart_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStartEnd_Are_Valid_AterTextChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
Assert.True(target.SelectionStart <= "123".Length);
Assert.True(target.SelectionEnd <= "123".Length);
}
}
[Fact]
public void SelectedText_Changes_OnSelectionChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
Assert.True(target.SelectedText == "");
target.SelectionStart = 2;
target.SelectionEnd = 4;
Assert.True(target.SelectedText == "23");
}
}
[Fact]
public void SelectedText_EditsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectedText = "AA";
Assert.True(target.Text == "AA0123");
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "BB";
Assert.True(target.Text == "ABB123");
}
}
[Fact]
public void SelectedText_CanClearText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "";
Assert.True(target.Text == "03");
}
}
[Fact]
public void SelectedText_NullClearsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = null;
Assert.True(target.Text == "03");
}
}
[Fact]
public void CoerceCaretIndex_Doesnt_Cause_Exception_with_malformed_line_ending()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789\r"
};
target.CaretIndex = 11;
Assert.True(true);
}
}
[Theory]
[InlineData(Key.Up)]
[InlineData(Key.Down)]
[InlineData(Key.Home)]
[InlineData(Key.End)]
public void Textbox_doesnt_crash_when_Receives_input_and_template_not_applied(Key key)
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
IsVisible = false
};
var root = new TestRoot { Child = target1 };
target1.Focus();
Assert.True(target1.IsFocused);
RaiseKeyEvent(target1, key, KeyModifiers.None);
}
}
[Fact]
public void TextBox_GotFocus_And_LostFocus_Work_Properly()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
var gfcount = 0;
var lfcount = 0;
target1.GotFocus += (s, e) => gfcount++;
target2.LostFocus += (s, e) => lfcount++;
target2.Focus();
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
Assert.Equal(1, gfcount);
Assert.Equal(1, lfcount);
}
}
[Fact]
public void TextBox_CaretIndex_Persists_When_Focus_Lost()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target2.Focus();
target2.CaretIndex = 2;
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.Equal(2, target2.CaretIndex);
}
}
[Fact]
public void TextBox_Reveal_Password_Reset_When_Lost_Focus()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
PasswordChar = '*'
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target1.Focus();
target1.RevealPassword = true;
target2.Focus();
Assert.False(target1.RevealPassword);
}
}
[Fact]
public void Setting_Bound_Text_To_Null_Works()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1 { Bar = "bar" };
var target = new TextBox { DataContext = source };
target.Bind(TextBox.TextProperty, new Binding("Bar"));
Assert.Equal("bar", target.Text);
source.Bar = null;
Assert.Null(target.Text);
}
}
[Theory]
[InlineData("abc", "d", 3, 0, 0, false, "abc")]
[InlineData("abc", "dd", 4, 3, 3, false, "abcd")]
[InlineData("abc", "ddd", 3, 0, 2, true, "ddc")]
[InlineData("abc", "dddd", 4, 1, 3, true, "addd")]
[InlineData("abc", "ddddd", 5, 3, 3, true, "abcdd")]
public void MaxLength_Works_Properly(
string initalText,
string textInput,
int maxLength,
int selectionStart,
int selectionEnd,
bool fromClipboard,
string expected)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = initalText,
MaxLength = maxLength,
SelectionStart = selectionStart,
SelectionEnd = selectionEnd
};
if (fromClipboard)
{
AvaloniaLocator.CurrentMutable.Bind<IClipboard>().ToSingleton<ClipboardStub>();
var clipboard = AvaloniaLocator.CurrentMutable.GetService<IClipboard>();
clipboard.SetTextAsync(textInput).GetAwaiter().GetResult();
RaiseKeyEvent(target, Key.V, KeyModifiers.Control);
clipboard.ClearAsync().GetAwaiter().GetResult();
}
else
{
RaiseTextEvent(target, textInput);
}
Assert.Equal(expected, target.Text);
}
}
[Theory]
[InlineData(Key.X, KeyModifiers.Control)]
[InlineData(Key.Back, KeyModifiers.None)]
[InlineData(Key.Delete, KeyModifiers.None)]
[InlineData(Key.Tab, KeyModifiers.None)]
[InlineData(Key.Enter, KeyModifiers.None)]
public void Keys_Allow_Undo(Key key, KeyModifiers modifiers)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123",
AcceptsReturn = true,
AcceptsTab = true
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
AvaloniaLocator.CurrentMutable
.Bind<Input.Platform.IClipboard>().ToSingleton<ClipboardStub>();
RaiseKeyEvent(target, key, modifiers);
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control); // undo
Assert.True(target.Text == "0123");
}
}
private static TestServices FocusServices => TestServices.MockThreadingInterface.With(
focusManager: new FocusManager(),
keyboardDevice: () => new KeyboardDevice(),
keyboardNavigation: new KeyboardNavigationHandler(),
inputManager: new InputManager(),
renderInterface: new MockPlatformRenderInterface(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl(),
standardCursorFactory: Mock.Of<ICursorFactory>());
private static TestServices Services => TestServices.MockThreadingInterface.With(
standardCursorFactory: Mock.Of<ICursorFactory>());
private IControlTemplate CreateTemplate()
{
return new FuncControlTemplate<TextBox>((control, scope) =>
new TextPresenter
{
Name = "PART_TextPresenter",
[!!TextPresenter.TextProperty] = new Binding
{
Path = "Text",
Mode = BindingMode.TwoWay,
Priority = BindingPriority.TemplatedParent,
RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
},
}.RegisterInNameScope(scope));
}
private void RaiseKeyEvent(TextBox textBox, Key key, KeyModifiers inputModifiers)
{
textBox.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
KeyModifiers = inputModifiers,
Key = key
});
}
private void RaiseTextEvent(TextBox textBox, string text)
{
textBox.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = text
});
}
private class Class1 : NotifyingBase
{
private int _foo;
private string _bar;
public int Foo
{
get { return _foo; }
set { _foo = value; RaisePropertyChanged(); }
}
public string Bar
{
get { return _bar; }
set { _bar = value; RaisePropertyChanged(); }
}
}
private class ClipboardStub : IClipboard // in order to get tests working that use the clipboard
{
private string _text;
public Task<string> GetTextAsync() => Task.FromResult(_text);
public Task SetTextAsync(string text)
{
_text = text;
return Task.CompletedTask;
}
public Task ClearAsync()
{
_text = null;
return Task.CompletedTask;
}
public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
public Task<string[]> GetFormatsAsync() => Task.FromResult(Array.Empty<string>());
public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
}
private class TestContextMenu : ContextMenu
{
public TestContextMenu()
{
IsOpen = true;
}
}
}
}
| |
// 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;
using System.ComponentModel;
using System.Globalization;
using System.Text;
namespace System.DirectoryServices.Protocols
{
public class DirectoryAttribute : CollectionBase
{
private string _attributeName = "";
internal bool _isSearchResult = false;
// Does not request Unicode byte order mark prefix be emitted, but turn on error detection.
private static readonly UTF8Encoding s_utf8EncoderWithErrorDetection = new UTF8Encoding(false, true);
// No Error detection.
private static readonly UTF8Encoding s_encoder = new UTF8Encoding();
public DirectoryAttribute()
{
}
public DirectoryAttribute(string name, string value) : this(name, (object)value)
{
}
public DirectoryAttribute(string name, byte[] value) : this(name, (object)value)
{
}
public DirectoryAttribute(string name, Uri value) : this(name, (object)value)
{
}
internal DirectoryAttribute(string name, object value) : this()
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
Name = name;
Add(value);
}
public DirectoryAttribute(string name, params object[] values) : this()
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (values == null)
throw new ArgumentNullException(nameof(values));
Name = name;
for (int i = 0; i < values.Length; i++)
{
Add(values[i]);
}
}
public string Name
{
get => _attributeName;
set => _attributeName = value ?? throw new ArgumentNullException(nameof(value));
}
public object[] GetValues(Type valuesType)
{
// Return the binary value.
if (valuesType == typeof(byte[]))
{
int count = List.Count;
byte[][] results = new byte[count][];
for (int i = 0; i < count; i++)
{
if (List[i] is string)
{
results[i] = s_encoder.GetBytes((string)List[i]);
}
else if (List[i] is byte[])
{
results[i] = (byte[])List[i];
}
else
{
throw new NotSupportedException(SR.DirectoryAttributeConversion);
}
}
return results;
}
// Return the string value.
else if (valuesType == typeof(string))
{
int count = List.Count;
string[] results = new string[count];
for (int i = 0; i < count; i++)
{
if (List[i] is string)
{
results[i] = (string)List[i];
}
else if (List[i] is byte[])
{
results[i] = s_encoder.GetString((byte[])List[i]);
}
else
{
throw new NotSupportedException(SR.DirectoryAttributeConversion);
}
}
return results;
}
throw new ArgumentException(SR.ValidDirectoryAttributeType, nameof(valuesType));
}
public object this[int index]
{
get
{
if (!_isSearchResult)
{
return List[index];
}
if (List[index] is byte[] temp)
{
try
{
return s_utf8EncoderWithErrorDetection.GetString(temp);
}
catch (ArgumentException)
{
return List[index];
}
}
// This hould not happen.
return List[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
else if (!(value is string) && !(value is byte[]) && !(value is Uri))
{
throw new ArgumentException(SR.ValidValueType, nameof(value));
}
List[index] = value;
}
}
public int Add(byte[] value) => Add((object)value);
public int Add(string value) => Add((object)value);
public int Add(Uri value) => Add((object)value);
internal int Add(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!(value is string) && !(value is byte[]) && !(value is Uri))
{
throw new ArgumentException(SR.ValidValueType, nameof(value));
}
return List.Add(value);
}
public void AddRange(object[] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (!(values is string[]) && !(values is byte[][]) && !(values is Uri[]))
{
throw new ArgumentException(SR.ValidValuesType, nameof(values));
}
for (int i = 0; i < values.Length; i++)
{
if (values[i] == null)
{
throw new ArgumentException(SR.NullValueArray, nameof(values));
}
}
InnerList.AddRange(values);
}
public bool Contains(object value) => List.Contains(value);
public void CopyTo(object[] array, int index) => List.CopyTo(array, index);
public int IndexOf(object value) => List.IndexOf(value);
public void Insert(int index, byte[] value) => Insert(index, (object)value);
public void Insert(int index, string value) => Insert(index, (object)value);
public void Insert(int index, Uri value) => Insert(index, (object)value);
private void Insert(int index, object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List.Insert(index, value);
}
public void Remove(object value) => List.Remove(value);
protected override void OnValidate(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!(value is string) && !(value is byte[]) && !(value is Uri))
{
throw new ArgumentException(SR.ValidValueType, nameof(value));
}
}
}
public class DirectoryAttributeModification : DirectoryAttribute
{
private DirectoryAttributeOperation _attributeOperation = DirectoryAttributeOperation.Replace;
public DirectoryAttributeModification()
{
}
public DirectoryAttributeOperation Operation
{
get => _attributeOperation;
set
{
if (value < DirectoryAttributeOperation.Add || value > DirectoryAttributeOperation.Replace)
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DirectoryAttributeOperation));
}
_attributeOperation = value;
}
}
}
public class SearchResultAttributeCollection : DictionaryBase
{
internal SearchResultAttributeCollection() { }
public DirectoryAttribute this[string attributeName]
{
get
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
object objectName = attributeName.ToLower(CultureInfo.InvariantCulture);
return (DirectoryAttribute)InnerHashtable[objectName];
}
}
public ICollection AttributeNames => Dictionary.Keys;
public ICollection Values => Dictionary.Values;
internal void Add(string name, DirectoryAttribute value)
{
Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value);
}
public bool Contains(string attributeName)
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
object objectName = attributeName.ToLower(CultureInfo.InvariantCulture);
return Dictionary.Contains(objectName);
}
public void CopyTo(DirectoryAttribute[] array, int index) => Dictionary.Values.CopyTo(array, index);
}
public class DirectoryAttributeCollection : CollectionBase
{
public DirectoryAttributeCollection()
{
}
public DirectoryAttribute this[int index]
{
get => (DirectoryAttribute)List[index];
set => List[index] = value ?? throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
public int Add(DirectoryAttribute attribute)
{
if (attribute == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
return List.Add(attribute);
}
public void AddRange(DirectoryAttribute[] attributes)
{
if (attributes == null)
{
throw new ArgumentNullException(nameof(attributes));
}
foreach (DirectoryAttribute attribute in attributes)
{
if (attribute == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
}
InnerList.AddRange(attributes);
}
public void AddRange(DirectoryAttributeCollection attributeCollection)
{
if (attributeCollection == null)
{
throw new ArgumentNullException(nameof(attributeCollection));
}
int currentCount = attributeCollection.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
Add(attributeCollection[i]);
}
}
public bool Contains(DirectoryAttribute value) => List.Contains(value);
public void CopyTo(DirectoryAttribute[] array, int index) => List.CopyTo(array, index);
public int IndexOf(DirectoryAttribute value) => List.IndexOf(value);
public void Insert(int index, DirectoryAttribute value)
{
if (value == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
List.Insert(index, value);
}
public void Remove(DirectoryAttribute value) => List.Remove(value);
protected override void OnValidate(object value)
{
if (value == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
if (!(value is DirectoryAttribute))
{
throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryAttribute)), nameof(value));
}
}
}
public class DirectoryAttributeModificationCollection : CollectionBase
{
public DirectoryAttributeModificationCollection()
{
}
public DirectoryAttributeModification this[int index]
{
get => (DirectoryAttributeModification)List[index];
set => List[index] = value ?? throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
public int Add(DirectoryAttributeModification attribute)
{
if (attribute == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
return List.Add(attribute);
}
public void AddRange(DirectoryAttributeModification[] attributes)
{
if (attributes == null)
{
throw new ArgumentNullException(nameof(attributes));
}
foreach (DirectoryAttributeModification attribute in attributes)
{
if (attribute == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
}
InnerList.AddRange(attributes);
}
public void AddRange(DirectoryAttributeModificationCollection attributeCollection)
{
if (attributeCollection == null)
{
throw new ArgumentNullException(nameof(attributeCollection));
}
int currentCount = attributeCollection.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
Add(attributeCollection[i]);
}
}
public bool Contains(DirectoryAttributeModification value) => List.Contains(value);
public void CopyTo(DirectoryAttributeModification[] array, int index) => List.CopyTo(array, index);
public int IndexOf(DirectoryAttributeModification value) => List.IndexOf(value);
public void Insert(int index, DirectoryAttributeModification value)
{
if (value == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
List.Insert(index, value);
}
public void Remove(DirectoryAttributeModification value) => List.Remove(value);
protected override void OnValidate(object value)
{
if (value == null)
{
throw new ArgumentException(SR.NullDirectoryAttributeCollection);
}
if (!(value is DirectoryAttributeModification))
{
throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryAttributeModification)), nameof(value));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class GameManager : MonoBehaviour
{
public GameObject plotPrefab;
public GameObject soulPrefab;
public PlayerManager playerManager;
public Camera mainCamera;
public Canvas GUICanvas;
private GameObject selectedSoul;
public GameObject selectedImage;
public bool plotIsSelected;
public bool soulIsSelected;
public GameObject soulMenu;
public GameObject characterMenu;
private Vector3 prevMousePosition;
public Vector4 limit;
public Vector2 distanceTraveled = new Vector2(0, 0);
private bool canMove;
private bool quickHarvest = false;
//private Button quickHarvestButton;
private PointerEventData pointerData;
private List<RaycastResult> rayResults;
private string initialTag;
private int initialRay;
public GameObject CharacterMenu;
public GameObject selectedGrid;
public List<GameObject> allSouls;
public List<GameObject> allPlots;
// Use this for initialization
void Start ()
{
selectedSoul = null;
soulIsSelected = false;
LoadSave();
plotIsSelected = false;
selectedImage.SetActive(false);
rayResults = new List<RaycastResult>();
characterMenu.GetComponent<CharacterMenu>().Hide();
initialTag = "";
initialRay = 0;
//quickHarvestButton = GameObject.Find("GUI").transform.FindChild("QuickHarvest").GetComponent<Button>();
}
// Update is called once per frame
void Update ()
{
//Debug.Log(selectedSoul);
if ((selectedSoul == null || !soulIsSelected) && !plotIsSelected)
{
soulMenu.GetComponent<SoulMenu>().Hide();
soulIsSelected = false;
selectedSoul = null;
selectedImage.SetActive(false);
}
if(soulIsSelected)
{
soulMenu.transform.GetChild(1).GetComponent<Slider>().value = selectedSoul.GetComponent<Soul>().lifespan;
soulMenu.transform.GetChild(1).GetComponent<Slider>().transform.GetChild(1).GetChild(0).GetComponent<Image>().color = new Color(1-(selectedSoul.GetComponent<Soul>().lifespan / selectedSoul.GetComponent<Soul>().MaxLifespan), selectedSoul.GetComponent<Soul>().lifespan/ selectedSoul.GetComponent<Soul>().MaxLifespan, 0, 1);
soulMenu.transform.GetChild(2).GetComponent<Text>().text = ((int)selectedSoul.GetComponent<Soul>().lifespan).ToString() + "s left alive";
}
if (Input.GetMouseButtonDown(0))
{
pointerData = new PointerEventData(EventSystem.current);
pointerData.position = Input.mousePosition;
EventSystem.current.RaycastAll(pointerData, rayResults);
prevMousePosition = Input.mousePosition;
if(rayResults.Count > 0)
{
initialTag = rayResults[0].gameObject.tag;
}
initialRay = rayResults.Count;
}
if(Input.GetMouseButton(0))
{
//click on nothing
if (initialRay == 0)
{
soulIsSelected = false;
playerManager.selectedPlot = null;
selectedGrid = null;
}
//click on ground
else if(initialTag == "PlotPoint")
{
//Debug.Log("soul is not clicked");
soulIsSelected = false;
playerManager.selectedPlot = null;
}
if(initialRay == 0 || initialTag == "Soul")
{
plotIsSelected = false;
}
if (canMove)
{
/*if(distanceTraveled.x + (.25f * (prevMousePosition.x - Input.mousePosition.x)) < 30 && distanceTraveled.x + (.25f * (prevMousePosition.x - Input.mousePosition.x)) > -30)
{
Camera.main.transform.Translate((.15f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Cos(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), 0, (.15f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Sin(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), Space.World);
distanceTraveled.x += .15f * (prevMousePosition.x - Input.mousePosition.x);
}
if(distanceTraveled.y + (.25f * (prevMousePosition.y - Input.mousePosition.y)) < 30 && distanceTraveled.y + (.25f * (prevMousePosition.y - Input.mousePosition.y)) > -30)
{
Camera.main.transform.Translate(-(.15f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Sin(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), 0, (.15f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Cos(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), Space.World);
distanceTraveled.y += .15f * (prevMousePosition.y - Input.mousePosition.y);
}*/
Camera.main.transform.Translate((.15f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Cos(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), 0, (.15f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Sin(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), Space.World);
Camera.main.transform.Translate(-(.15f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Sin(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), 0, (.15f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Cos(Mathf.Deg2Rad * -Camera.main.transform.eulerAngles.y)), Space.World);
if (Camera.main.transform.position.x > 60)
{
Camera.main.transform.position = new Vector3(60, Camera.main.transform.position.y, Camera.main.transform.position.z);
}
if (Camera.main.transform.position.x < 0)
{
Camera.main.transform.position = new Vector3(0, Camera.main.transform.position.y, Camera.main.transform.position.z);
}
if (Camera.main.transform.position.z > 0)
{
Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, 0);
}
if (Camera.main.transform.position.z < -60)
{
Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, -60);
}
}
//combines the previous 2 lines into 1
//Camera.main.transform.Translate((.5f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Cos(Mathf.Deg2Rad * 40)) - (.5f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Sin(Mathf.Deg2Rad * 40)), 0, (.5f * (prevMousePosition.y - Input.mousePosition.y) * Mathf.Cos(Mathf.Deg2Rad * 40)) + (.5f * (prevMousePosition.x - Input.mousePosition.x) * Mathf.Sin(Mathf.Deg2Rad * 40)), Space.World);
if(canMove || Vector2.Distance(Input.mousePosition, prevMousePosition) > 10 && (initialRay == 0 || initialTag == "PlotPoint"))
{
prevMousePosition = Input.mousePosition;
canMove = true;
}
}
if(!Input.GetMouseButton(0))
{
canMove = false;
}
if (playerManager.selectedPlot == null && selectedGrid == null)
{
GameObject.Find("GUI").transform.FindChild("QuickHarvest").gameObject.SetActive(true);
GameObject.Find("GUI").transform.FindChild("ToPlayer").gameObject.SetActive(true);
}
else
{
GameObject.Find("GUI").transform.FindChild("QuickHarvest").gameObject.SetActive(false);
GameObject.Find("GUI").transform.FindChild("ToPlayer").gameObject.SetActive(false);
}
if (selectedGrid != null)
{
GameObject.Find("GUI").transform.FindChild("PlotSelect").gameObject.SetActive(true);
}
else
{
GameObject.Find("GUI").transform.FindChild("PlotSelect").gameObject.SetActive(false);
}
}
public void CloseSoulSelect()
{
playerManager.selectedPlot = null;
}
public void ClosePlotSelect()
{
selectedGrid = null;
}
public void SelectSoul(GameObject Soul)
{
playerManager.selectedPlot = null;
RectTransform GUIRect = GUICanvas.GetComponent<RectTransform>();
Vector2 viewPosition = mainCamera.WorldToViewportPoint(Soul.transform.position);
Vector2 soulScreenpos = new Vector2(((viewPosition.x * GUIRect.sizeDelta.x) - (GUIRect.sizeDelta.x * .5f)), ((viewPosition.y * GUIRect.sizeDelta.y) - (GUIRect.sizeDelta.y * .5f)));
selectedImage.GetComponent<RectTransform>().anchoredPosition = soulScreenpos;
selectedImage.SetActive(true);
selectedSoul = Soul;
soulIsSelected = true;
DisplaySelectedSoulInfo();
}
public void HarvestSelectedSoul()
{
selectedSoul.GetComponent<Soul>().Harvest();
selectedSoul = null;
GameObject.Find("GUI").transform.FindChild("QuickHarvest").gameObject.SetActive(true);
GameObject.Find("GUI").transform.FindChild("ToPlayer").gameObject.SetActive(true);
}
private void DisplaySelectedSoulInfo()
{
soulMenu.GetComponent<SoulMenu>().Show();
soulMenu.transform.GetChild(0).GetComponent<Text>().text = selectedSoul.GetComponent<Soul>().ectoPerSecond.ToString() + " Ecto per second";
soulMenu.transform.GetChild(1).GetComponent<Slider>().maxValue = selectedSoul.GetComponent<Soul>().MaxLifespan;
soulMenu.transform.GetChild(1).GetComponent<Slider>().value = selectedSoul.GetComponent<Soul>().lifespan;
soulMenu.transform.GetChild(2).GetComponent<Text>().text = ((int)selectedSoul.GetComponent<Soul>().lifespan).ToString() + "s left alive";
soulMenu.transform.GetChild(3).GetComponent<Text>().text = selectedSoul.GetComponent<Soul>().ectoPerHarvest.ToString() + " Ecto on Harvest";
}
public void ToggleQuickHarvest()
{
quickHarvest = !quickHarvest;
}
void OnApplicationFocus(bool gainedFocus)
{
if (!gainedFocus) SaveGame();
}
void OnApplicationPause(bool pausing)
{
if (pausing) SaveGame();
}
void OnApplicationQuit()
{
SaveGame();
}
public void SaveGame()
{
try
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
FileStream file = File.Create(Path.Combine(Application.persistentDataPath, "newsave3.sav"));
SaveData save = new SaveData() {
CreationTimestamp = System.DateTime.UtcNow,
Ectoplasm = playerManager.Ectoplasm,
Level = playerManager.Level,
Experience = playerManager.Experience,
ScytheRank = playerManager.scytheRank,
Plots = new Dictionary<int, SerializablePlot>()
};
foreach(var plotObj in playerManager.Plots)
{
var plot = plotObj.GetComponent<Plot>();
SerializablePlot splot = new SerializablePlot() { Souls = new SerializableSoul[plot.SoulContent.Count] };
switch(plot.cost)
{
case 35:
splot.Type = SerializablePlot.PlotType.Base;
break;
case 125:
splot.Type = SerializablePlot.PlotType.City;
break;
case 300:
splot.Type = SerializablePlot.PlotType.Moon;
break;
}
for(int i = 0; i < plot.SoulContent.Count; i++)
{
var soul = plot.SoulContent[i].GetComponent<Soul>();
SerializableSoul ssoul = new SerializableSoul() {
EctoPerHarvest = soul.ectoPerHarvest,
EctoPerSecond = soul.ectoPerSecond,
Lifespan = soul.lifespan,
TimeToRipe = soul.timeToRipe,
BaseColor = soul.baseColor,
MatureColor = soul.matureColor
};
switch(soul.cost)
{
case 10:
ssoul.Type = SerializableSoul.SoulType.Base;
break;
case 25:
ssoul.Type = SerializableSoul.SoulType.College;
break;
case 50:
ssoul.Type = SerializableSoul.SoulType.Construction;
break;
case 100:
ssoul.Type = SerializableSoul.SoulType.Astronaut;
break;
}
splot.Souls[i] = ssoul;
}
var parentGrid = plotObj.GetComponentInParent<GridPart>();
save.Plots.Add(parentGrid.GetInstanceID(), splot);
}
bf.Serialize(file, save);
file.Close();
}
catch (IOException ex)
{
Debug.Log("There was an error thrown by the OS when trying to save! Exception: " + ex.Message);
}
}
private void LoadSave()
{
try
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
FileStream file = File.OpenRead(Path.Combine(Application.persistentDataPath, "newsave3.sav"));
object rawsave = bf.Deserialize(file);
SaveData save = (SaveData)rawsave;
playerManager.ectoplasm = save.Ectoplasm;
for(int i = save.Level; i > 1; i--)
{
playerManager.LevelUp();
}
playerManager.scytheRank = save.ScytheRank;
playerManager.experience = save.Experience;
TimeSpan ts = DateTime.UtcNow - save.CreationTimestamp;
float deltaTime = (float)ts.TotalSeconds;
foreach(var plot in save.Plots)
{
GameObject instantiated = playerManager.AddPlotDirect(allPlots[(int)plot.Value.Type], plot.Key);
Plot newPlot = instantiated.GetComponent<Plot>();
foreach(var savedSoul in plot.Value.Souls)
{
GameObject instantiatedSoul = newPlot.AddToPlotDirect(allSouls[(int)savedSoul.Type]);
Soul newSoul = instantiatedSoul.GetComponent<Soul>();
newSoul.ectoPerHarvest = savedSoul.EctoPerHarvest;
newSoul.ectoPerSecond = savedSoul.EctoPerSecond;
newSoul.lifespan = savedSoul.Lifespan - deltaTime;
newSoul.timeToRipe = savedSoul.TimeToRipe - deltaTime;
newSoul.baseColor = savedSoul.BaseColor;
newSoul.transform.GetComponent<Image>().color = savedSoul.BaseColor;
newSoul.matureColor = savedSoul.MatureColor;
if (newSoul.lifespan < 0) playerManager.ectoplasm += savedSoul.Lifespan * newSoul.ectoPerSecond;
else playerManager.ectoplasm += deltaTime * newSoul.ectoPerSecond;
}
}
file.Close();
}
catch(FileNotFoundException)
{
Debug.Log("No save file found, ignoring.");
}
catch (IOException ex)
{
Debug.Log("There was an error thrown by the OS when trying to load the save file! Exception: " + ex.Message);
}
}
public bool QuickHarvest
{
get
{
return quickHarvest;
}
}
public void SetCharacterMenu(bool activation)
{
if(activation)
{
characterMenu.GetComponent<CharacterMenu>().Show();
}
else
{
characterMenu.GetComponent<CharacterMenu>().Hide();
activation = true;
}
}
public void SetCredits(bool active)
{
GameObject.Find("Credits").SetActive(active);
}
/// <summary>
/// Need an easy way to exit the game to avoid Android doing stupid things
/// </summary>
public void Exit()
{
Application.Quit();
}
}
| |
/*
* 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 OpenSim.Region.ScriptEngine.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Lifetime;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject, IScript
{
private Dictionary<string, MethodInfo> inits = new Dictionary<string, MethodInfo>();
// private ScriptSponsor m_sponser;
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
// Infinite
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
#if DEBUG
// For tracing GC while debugging
public static bool GCDummy = false;
~ScriptBaseClass()
{
GCDummy = true;
}
#endif
public ScriptBaseClass()
{
m_Executor = new Executor(this);
MethodInfo[] myArrayMethodInfo = GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo mi in myArrayMethodInfo)
{
if (mi.Name.Length > 7 && mi.Name.Substring(0, 7) == "ApiType")
{
string type = mi.Name.Substring(7);
inits[type] = mi;
}
}
// m_sponser = new ScriptSponsor();
}
private Executor m_Executor = null;
public int GetStateEventFlags(string state)
{
return (int)m_Executor.GetStateEventFlags(state);
}
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
m_Executor.ExecuteEvent(state, FunctionName, args);
}
public string[] GetApis()
{
string[] apis = new string[inits.Count];
inits.Keys.CopyTo(apis, 0);
return apis;
}
private Dictionary<string, object> m_InitialValues =
new Dictionary<string, object>();
private Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
public void InitApi(string api, IScriptApi data)
{
if (!inits.ContainsKey(api))
return;
//ILease lease = (ILease)RemotingServices.GetLifetimeService(data as MarshalByRefObject);
//RemotingServices.GetLifetimeService(data as MarshalByRefObject);
// lease.Register(m_sponser);
MethodInfo mi = inits[api];
Object[] args = new Object[1];
args[0] = data;
mi.Invoke(this, args);
m_InitialValues = GetVars();
}
public virtual void StateChange(string newState)
{
}
public void Close()
{
// m_sponser.Close();
}
public Dictionary<string, object> GetVars()
{
Dictionary<string, object> vars = new Dictionary<string, object>();
if (m_Fields == null)
return vars;
m_Fields.Clear();
Type t = GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo field in fields)
{
m_Fields[field.Name] = field;
if (field.FieldType == typeof(LSL_Types.list)) // ref type, copy
{
LSL_Types.list v = (LSL_Types.list)field.GetValue(this);
Object[] data = new Object[v.Data.Length];
Array.Copy(v.Data, 0, data, 0, v.Data.Length);
LSL_Types.list c = new LSL_Types.list();
c.Data = data;
vars[field.Name] = c;
}
else if (field.FieldType == typeof(LSL_Types.LSLInteger) ||
field.FieldType == typeof(LSL_Types.LSLString) ||
field.FieldType == typeof(LSL_Types.LSLFloat) ||
field.FieldType == typeof(Int32) ||
field.FieldType == typeof(Double) ||
field.FieldType == typeof(Single) ||
field.FieldType == typeof(String) ||
field.FieldType == typeof(Byte) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(LSL_Types.Vector3) ||
field.FieldType == typeof(LSL_Types.Quaternion))
{
vars[field.Name] = field.GetValue(this);
}
}
return vars;
}
public void SetVars(Dictionary<string, object> vars)
{
foreach (KeyValuePair<string, object> var in vars)
{
if (m_Fields.ContainsKey(var.Key))
{
if (m_Fields[var.Key].FieldType == typeof(LSL_Types.list))
{
LSL_Types.list v = (LSL_Types.list)m_Fields[var.Key].GetValue(this);
Object[] data = ((LSL_Types.list)var.Value).Data;
v.Data = new Object[data.Length];
Array.Copy(data, 0, v.Data, 0, data.Length);
m_Fields[var.Key].SetValue(this, v);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLInteger) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLString) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLFloat) ||
m_Fields[var.Key].FieldType == typeof(Int32) ||
m_Fields[var.Key].FieldType == typeof(Double) ||
m_Fields[var.Key].FieldType == typeof(Single) ||
m_Fields[var.Key].FieldType == typeof(String) ||
m_Fields[var.Key].FieldType == typeof(Byte) ||
m_Fields[var.Key].FieldType == typeof(short) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Vector3) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Quaternion)
)
{
m_Fields[var.Key].SetValue(this, var.Value);
}
}
}
}
public void ResetVars()
{
SetVars(m_InitialValues);
}
public void NoOp()
{
// Does what is says on the packet. Nowt, nada, nothing.
// Required for insertion after a jump label to do what it says on the packet!
// With a bit of luck the compiler may even optimize it out.
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly Logger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper();
/// <summary>
/// Constructor
/// </summary>
public AzureSilo()
{
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
logger = LogManager.GetLogger("OrleansAzureSilo", LoggerType.Runtime);
}
public static ClusterConfiguration DefaultConfiguration()
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = AzureClient.GetDeploymentId();
config.Globals.DataConnectionString = AzureClient.GetDataConnectionString();
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start()
{
return Start(null);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string deploymentId = null, string connectionString = null)
{
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Check if deployment id was specified
if (deploymentId == null)
deploymentId = serviceRuntimeWrapper.DeploymentId;
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialise this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, 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.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IDisposable
{
private object lockObject = new object();
private List<Layout> allLayouts;
private bool allLayoutsAreThreadAgnostic;
private bool scannedForLayouts;
private Exception initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='10' />
public string Name { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot
{
get { return this.lockObject; }
}
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized
{
get
{
if (this.isInitialized)
return true; // Initialization has completed
// Lets wait for initialization to complete, and then check again
lock (this.SyncRoot)
{
return this.isInitialized;
}
}
}
private volatile bool isInitialized;
/// <summary>
/// Get all used layouts in this target.
/// </summary>
/// <returns></returns>
internal List<Layout> GetAllLayouts()
{
if (!scannedForLayouts)
{
lock (this.SyncRoot)
{
FindAllLayouts();
}
}
return allLayouts;
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation == null)
{
throw new ArgumentNullException("asyncContinuation");
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
// In case target was Closed
asyncContinuation(null);
return;
}
try
{
this.FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
if (this.allLayoutsAreThreadAgnostic)
return;
// Not all Layouts support concurrent threads, so we have to protect them
lock (this.SyncRoot)
{
if (!this.isInitialized)
return;
if (this.allLayouts != null)
{
foreach (Layout layout in this.allLayouts)
{
layout.Precalculate(logEvent);
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
if (targetAttribute != null)
{
return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
}
return this.GetType().Name;
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
if (!this.IsInitialized)
{
lock (this.SyncRoot)
{
logEvent.Continuation(null);
}
return;
}
if (this.initializeException != null)
{
lock (this.SyncRoot)
{
logEvent.Continuation(this.CreateInitException());
}
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation);
this.WriteAsyncThreadSafe(wrappedLogEvent);
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
if (logEvents == null || logEvents.Length == 0)
{
return;
}
if (!this.IsInitialized)
{
lock (this.SyncRoot)
{
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
}
return;
}
if (this.initializeException != null)
{
lock (this.SyncRoot)
{
foreach (var ev in logEvents)
{
ev.Continuation(this.CreateInitException());
}
}
return;
}
var wrappedEvents = new AsyncLogEventInfo[logEvents.Length];
for (int i = 0; i < logEvents.Length; ++i)
{
wrappedEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
this.WriteAsyncThreadSafe(wrappedEvents);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = configuration;
if (!this.IsInitialized)
{
PropertyHelper.CheckRequiredParameters(this);
try
{
this.InitializeTarget();
this.initializeException = null;
if (!scannedForLayouts)
{
InternalLogger.Debug("InitializeTarget is done but not scanned For Layouts");
//this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here.
FindAllLayouts();
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error initializing target '{0}'.", this);
this.initializeException = exception;
if (exception.MustBeRethrown())
{
throw;
}
}
finally
{
this.isInitialized = true;
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = null;
if (this.IsInitialized)
{
this.isInitialized = false;
try
{
if (this.initializeException == null)
{
// if Init succeeded, call Close()
this.CloseTarget();
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error closing target '{0}'.", this);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
{
if (logEventInfos.Length == 0)
{
continuation(null);
}
else
{
var wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Length];
int remaining = logEventInfos.Length;
for (int i = 0; i < logEventInfos.Length; ++i)
{
AsyncContinuation originalContinuation = logEventInfos[i].Continuation;
AsyncContinuation wrappedContinuation = ex =>
{
originalContinuation(ex);
if (0 == Interlocked.Decrement(ref remaining))
{
continuation(null);
}
};
wrappedLogEventInfos[i] = logEventInfos[i].LogEvent.WithContinuation(wrappedContinuation);
}
this.WriteAsyncLogEvents(wrappedLogEventInfos);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.CloseTarget();
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected virtual void InitializeTarget()
{
//rescan as amount layouts can be changed.
FindAllLayouts();
}
private void FindAllLayouts()
{
this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count);
bool foundNotThreadAgnostic = false;
foreach (Layout layout in this.allLayouts)
{
if (!layout.IsThreadAgnostic)
{
foundNotThreadAgnostic = true;
break;
}
}
this.allLayoutsAreThreadAgnostic = !foundNotThreadAgnostic;
this.scannedForLayouts = true;
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the log target.
/// classes.
/// </summary>
/// <param name="logEvent">
/// Logging event to be written out.
/// </param>
protected virtual void Write(LogEventInfo logEvent)
{
// do nothing
}
/// <summary>
/// Writes log event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
this.MergeEventProperties(logEvent.LogEvent);
this.Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes a log event to the log target, in a thread safe manner.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
// In case target was Closed
logEvent.Continuation(null);
return;
}
try
{
this.Write(logEvent);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(AsyncLogEventInfo[] logEvents)
{
for (int i = 0; i < logEvents.Length; ++i)
{
this.Write(logEvents[i]);
}
}
/// <summary>
/// Writes an array of logging events to the log target, in a thread safe manner.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo[] logEvents)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
// In case target was Closed
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
return;
}
try
{
this.Write(logEvents);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of synchronous failure, assume that nothing is running asynchronously
foreach (var ev in logEvents)
{
ev.Continuation(exception);
}
}
}
}
private Exception CreateInitException()
{
return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
}
/// <summary>
/// Merges (copies) the event context properties from any event info object stored in
/// parameters of the given event info object.
/// </summary>
/// <param name="logEvent">The event info object to perform the merge to.</param>
protected void MergeEventProperties(LogEventInfo logEvent)
{
if (logEvent.Parameters == null || logEvent.Parameters.Length == 0)
{
return;
}
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < logEvent.Parameters.Length; ++i)
{
var logEventParameter = logEvent.Parameters[i] as LogEventInfo;
if (logEventParameter != null && logEventParameter.HasProperties)
{
foreach (var key in logEventParameter.Properties.Keys)
{
logEvent.Properties.Add(key, logEventParameter.Properties[key]);
}
logEventParameter.Properties.Clear();
}
}
}
/// <summary>
/// Register a custom Target.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Target.</typeparam>
/// <param name="name"> Name of the Target.</param>
public static void Register<T>(string name)
where T : Target
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Target.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="targetType"> Type of the Target.</param>
/// <param name="name"> Name of the Target.</param>
public static void Register(string name, Type targetType)
{
ConfigurationItemFactory.Default.Targets
.RegisterDefinition(name, targetType);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using Irony.Ast;
namespace Irony.Parsing
{
//Microsoft.Scripting.Math.BigInteger;
using Complex64 = Complex;
// Microsoft.Scripting.Math.Complex64;
[Flags]
public enum NumberOptions
{
None = 0,
Default = None,
AllowStartEndDot = 0x01, //python : http://docs.python.org/ref/floating.html
IntOnly = 0x02,
NoDotAfterInt = 0x04, //for use with IntOnly flag; essentially tells terminal to avoid matching integer if
// it is followed by dot (or exp symbol) - leave to another terminal that will handle float numbers
AllowSign = 0x08,
DisableQuickParse = 0x10,
AllowLetterAfter = 0x20,
// allow number be followed by a letter or underscore; by default this flag is not set, so "3a" would not be
// recognized as number followed by an identifier
AllowUnderscore = 0x40, // Ruby allows underscore inside number: 1_234
//The following should be used with base-identifying prefixes
Binary = 0x0100, //e.g. GNU GCC C Extension supports binary number literals
Octal = 0x0200,
Hex = 0x0400
}
public class NumberLiteral : CompoundTerminalBase
{
//Flags for internal use
public enum NumberFlagsInternal : short
{
HasDot = 0x1000,
HasExp = 0x2000
}
//nested helper class
public class ExponentsTable : Dictionary<char, TypeCode>
{
}
#region Public Consts
//currently using TypeCodes for identifying numeric types
public const TypeCode TypeCodeBigInt = (TypeCode) 30;
public const TypeCode TypeCodeImaginary = (TypeCode) 31;
#endregion
#region constructors and initialization
public NumberLiteral(string name) : this(name, NumberOptions.Default)
{
}
public NumberLiteral(string name, NumberOptions options, Type astNodeType) : this(name, options)
{
AstConfig.NodeType = astNodeType;
}
public NumberLiteral(string name, NumberOptions options, AstNodeCreator astNodeCreator) : this(name, options)
{
AstConfig.NodeCreator = astNodeCreator;
}
public NumberLiteral(string name, NumberOptions options) : base(name)
{
Options = options;
SetFlag(TermFlags.IsLiteral);
}
public void AddPrefix(string prefix, NumberOptions options)
{
PrefixFlags.Add(prefix, (short) options);
Prefixes.Add(prefix);
}
public void AddExponentSymbols(string symbols, TypeCode floatType)
{
foreach (var exp in symbols)
_exponentsTable[exp] = floatType;
}
#endregion
#region Public fields/properties: ExponentSymbols, Suffixes
public NumberOptions Options;
public char DecimalSeparator = '.';
//Default types are assigned to literals without suffixes; first matching type used
public TypeCode[] DefaultIntTypes = {TypeCode.Int32};
public TypeCode DefaultFloatType = TypeCode.Double;
private readonly ExponentsTable _exponentsTable = new ExponentsTable();
public bool IsSet(NumberOptions option)
{
return (Options & option) != 0;
}
#endregion
#region Private fields: _quickParseTerminators
#endregion
#region overrides
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
//Default Exponent symbols if table is empty
if (_exponentsTable.Count == 0 && !IsSet(NumberOptions.IntOnly))
{
_exponentsTable['e'] = DefaultFloatType;
_exponentsTable['E'] = DefaultFloatType;
}
if (EditorInfo == null)
EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None);
}
public override IList<string> GetFirsts()
{
var result = new StringList();
result.AddRange(Prefixes);
//we assume that prefix is always optional, so number can always start with plain digit
result.AddRange(new[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"});
// Python float numbers can start with a dot
if (IsSet(NumberOptions.AllowStartEndDot))
result.Add(DecimalSeparator.ToString());
if (IsSet(NumberOptions.AllowSign))
result.AddRange(new[] {"-", "+"});
return result;
}
//Most numbers in source programs are just one-digit instances of 0, 1, 2, and maybe others until 9
// so we try to do a quick parse for these, without starting the whole general process
protected override Token QuickParse(ParsingContext context, ISourceStream source)
{
if (IsSet(NumberOptions.DisableQuickParse)) return null;
var current = source.PreviewChar;
//it must be a digit followed by a whitespace or delimiter
if (!char.IsDigit(current)) return null;
if (!Grammar.IsWhitespaceOrDelimiter(source.NextPreviewChar))
return null;
var iValue = current - '0';
object value = null;
switch (DefaultIntTypes[0])
{
case TypeCode.Int32:
value = iValue;
break;
case TypeCode.UInt32:
value = (uint) iValue;
break;
case TypeCode.Byte:
value = (byte) iValue;
break;
case TypeCode.SByte:
value = (sbyte) iValue;
break;
case TypeCode.Int16:
value = (short) iValue;
break;
case TypeCode.UInt16:
value = (ushort) iValue;
break;
default:
return null;
}
source.PreviewPosition++;
return source.CreateToken(OutputTerminal, value);
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details)
{
base.InitDetails(context, details);
details.Flags = (short) Options;
}
protected override void ReadPrefix(ISourceStream source, CompoundTokenDetails details)
{
//check that is not a 0 followed by dot;
//this may happen in Python for number "0.123" - we can mistakenly take "0" as octal prefix
if (source.PreviewChar == '0' && source.NextPreviewChar == '.') return;
base.ReadPrefix(source, details);
} //method
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details)
{
//remember start - it may be different from source.TokenStart, we may have skipped prefix
var start = source.PreviewPosition;
var current = source.PreviewChar;
if (IsSet(NumberOptions.AllowSign) && (current == '-' || current == '+'))
{
details.Sign = current.ToString();
source.PreviewPosition++;
}
//Figure out digits set
var digits = GetDigits(details);
var isDecimal = !details.IsSet((short) (NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex));
var allowFloat = !IsSet(NumberOptions.IntOnly);
var foundDigits = false;
while (!source.EOF())
{
current = source.PreviewChar;
//1. If it is a digit, just continue going; the same for '_' if it is allowed
if (digits.IndexOf(current) >= 0 || IsSet(NumberOptions.AllowUnderscore) && current == '_')
{
source.PreviewPosition++;
foundDigits = true;
continue;
}
//2. Check if it is a dot in float number
var isDot = current == DecimalSeparator;
if (allowFloat && isDot)
{
//If we had seen already a dot or exponent, don't accept this one;
var hasDotOrExp = details.IsSet((short) (NumberFlagsInternal.HasDot | NumberFlagsInternal.HasExp));
if (hasDotOrExp) break; //from while loop
//In python number literals (NumberAllowPointFloat) a point can be the first and last character,
//We accept dot only if it is followed by a digit
if (digits.IndexOf(source.NextPreviewChar) < 0 && !IsSet(NumberOptions.AllowStartEndDot))
break; //from while loop
details.Flags |= (int) NumberFlagsInternal.HasDot;
source.PreviewPosition++;
continue;
}
//3. Check if it is int number followed by dot or exp symbol
var isExpSymbol = (details.ExponentSymbol == null) && _exponentsTable.ContainsKey(current);
if (!allowFloat && foundDigits && (isDot || isExpSymbol))
{
//If no partial float allowed then return false - it is not integer, let float terminal recognize it as float
if (IsSet(NumberOptions.NoDotAfterInt)) return false;
//otherwise break, it is integer and we're done reading digits
break;
}
//4. Only for decimals - check if it is (the first) exponent symbol
if (allowFloat && isDecimal && isExpSymbol)
{
var next = source.NextPreviewChar;
var nextIsSign = next == '-' || next == '+';
var nextIsDigit = digits.IndexOf(next) >= 0;
if (!nextIsSign && !nextIsDigit)
break; //Exponent should be followed by either sign or digit
//ok, we've got real exponent
details.ExponentSymbol = current.ToString(); //remember the exp char
details.Flags |= (int) NumberFlagsInternal.HasExp;
source.PreviewPosition++;
if (nextIsSign)
source.PreviewPosition++;
//skip +/- explicitly so we don't have to deal with them on the next iteration
continue;
}
//4. It is something else (not digit, not dot or exponent) - we're done
break; //from while loop
} //while
var end = source.PreviewPosition;
if (!foundDigits)
return false;
details.Body = source.Text.Substring(start, end - start);
return true;
}
protected internal override void OnValidateToken(ParsingContext context)
{
if (!IsSet(NumberOptions.AllowLetterAfter))
{
var current = context.Source.PreviewChar;
if (char.IsLetter(current) || current == '_')
{
context.CurrentToken = context.CreateErrorToken(Resources.ErrNoLetterAfterNum);
// "Number cannot be followed by a letter."
}
}
base.OnValidateToken(context);
}
protected override bool ConvertValue(CompoundTokenDetails details)
{
if (string.IsNullOrEmpty(details.Body))
{
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
AssignTypeCodes(details);
//check for underscore
if (IsSet(NumberOptions.AllowUnderscore) && details.Body.Contains("_"))
details.Body = details.Body.Replace("_", string.Empty);
//Try quick paths
switch (details.TypeCodes[0])
{
case TypeCode.Int32:
if (QuickConvertToInt32(details)) return true;
break;
case TypeCode.Double:
if (QuickConvertToDouble(details)) return true;
break;
}
//Go full cycle
details.Value = null;
foreach (var typeCode in details.TypeCodes)
{
switch (typeCode)
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCodeImaginary:
return ConvertToFloat(typeCode, details);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
if (details.Value == null) //if it is not done yet
TryConvertToLong(details, typeCode == TypeCode.UInt64);
//try to convert to Long/Ulong and place the result into details.Value field;
if (TryCastToIntegerType(typeCode, details))
//now try to cast the ULong value to the target type
return true;
break;
case TypeCodeBigInt:
if (ConvertToBigInteger(details)) return true;
break;
} //switch
}
return false;
} //method
private void AssignTypeCodes(CompoundTokenDetails details)
{
//Type could be assigned when we read suffix; if so, just exit
if (details.TypeCodes != null) return;
//Decide on float types
var hasDot = details.IsSet((short) (NumberFlagsInternal.HasDot));
var hasExp = details.IsSet((short) (NumberFlagsInternal.HasExp));
var isFloat = (hasDot || hasExp);
if (!isFloat)
{
details.TypeCodes = DefaultIntTypes;
return;
}
//so we have a float. If we have exponent symbol then use it to select type
if (hasExp)
{
TypeCode code;
if (_exponentsTable.TryGetValue(details.ExponentSymbol[0], out code))
{
details.TypeCodes = new[] {code};
return;
}
} //if hasExp
//Finally assign default float type
details.TypeCodes = new[] {DefaultFloatType};
}
#endregion
#region private utilities
private bool QuickConvertToInt32(CompoundTokenDetails details)
{
var radix = GetRadix(details);
if (radix == 10 && details.Body.Length > 10)
return false; //10 digits is maximum for int32; int32.MaxValue = 2 147 483 647
try
{
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
var iValue = 0;
if (radix == 10)
iValue = Convert.ToInt32(details.Body, CultureInfo.InvariantCulture);
else
iValue = Convert.ToInt32(details.Body, radix);
details.Value = iValue;
return true;
}
catch
{
return false;
}
} //method
private bool QuickConvertToDouble(CompoundTokenDetails details)
{
if (details.IsSet((short) (NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) return false;
if (details.IsSet((short) (NumberFlagsInternal.HasExp))) return false;
if (DecimalSeparator != '.') return false;
double dvalue;
if (!double.TryParse(details.Body, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dvalue))
return false;
details.Value = dvalue;
return true;
}
private bool ConvertToFloat(TypeCode typeCode, CompoundTokenDetails details)
{
//only decimal numbers can be fractions
if (details.IsSet((short) (NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex)))
{
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
var body = details.Body;
//Some languages allow exp symbols other than E. Check if it is the case, and change it to E
// - otherwise .NET conversion methods may fail
if (details.IsSet((short) NumberFlagsInternal.HasExp) && details.ExponentSymbol.ToUpper() != "E")
body = body.Replace(details.ExponentSymbol, "E");
//'.' decimal seperator required by invariant culture
if (details.IsSet((short) NumberFlagsInternal.HasDot) && DecimalSeparator != '.')
body = body.Replace(DecimalSeparator, '.');
switch (typeCode)
{
case TypeCode.Double:
case TypeCodeImaginary:
double dValue;
if (!double.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out dValue))
return false;
if (typeCode == TypeCodeImaginary)
details.Value = new Complex64(0, dValue);
else
details.Value = dValue;
return true;
case TypeCode.Single:
float fValue;
if (!float.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue))
return false;
details.Value = fValue;
return true;
case TypeCode.Decimal:
decimal decValue;
if (!decimal.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue))
return false;
details.Value = decValue;
return true;
} //switch
return false;
}
private bool TryCastToIntegerType(TypeCode typeCode, CompoundTokenDetails details)
{
if (details.Value == null) return false;
try
{
if (typeCode != TypeCode.UInt64)
details.Value = Convert.ChangeType(details.Value, typeCode, CultureInfo.InvariantCulture);
return true;
}
catch (Exception)
{
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, typeCode);
return false;
}
} //method
private bool TryConvertToLong(CompoundTokenDetails details, bool useULong)
{
try
{
var radix = GetRadix(details);
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
if (useULong)
details.Value = Convert.ToUInt64(details.Body, CultureInfo.InvariantCulture);
else
details.Value = Convert.ToInt64(details.Body, CultureInfo.InvariantCulture);
else if (useULong)
details.Value = Convert.ToUInt64(details.Body, radix);
else
details.Value = Convert.ToInt64(details.Body, radix);
return true;
}
catch (OverflowException)
{
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, TypeCode.Int64);
return false;
}
}
private bool ConvertToBigInteger(CompoundTokenDetails details)
{
//ignore leading zeros and sign
details.Body = details.Body.TrimStart('+').TrimStart('-').TrimStart('0');
if (string.IsNullOrEmpty(details.Body))
details.Body = "0";
var bodyLength = details.Body.Length;
var radix = GetRadix(details);
var wordLength = GetSafeWordLength(details);
var sectionCount = GetSectionCount(bodyLength, wordLength);
var numberSections = new ulong[sectionCount]; //big endian
try
{
var startIndex = details.Body.Length - wordLength;
for (var sectionIndex = sectionCount - 1; sectionIndex >= 0; sectionIndex--)
{
if (startIndex < 0)
{
wordLength += startIndex;
startIndex = 0;
}
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength));
else
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength),
radix);
startIndex -= wordLength;
}
}
catch
{
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
//produce big integer
var safeWordRadix = GetSafeWordRadix(details);
BigInteger bigIntegerValue = numberSections[0];
for (var i = 1; i < sectionCount; i++)
bigIntegerValue = checked(bigIntegerValue*safeWordRadix + numberSections[i]);
if (details.Sign == "-")
bigIntegerValue = -bigIntegerValue;
details.Value = bigIntegerValue;
return true;
}
private int GetRadix(CompoundTokenDetails details)
{
if (details.IsSet((short) NumberOptions.Hex))
return 16;
if (details.IsSet((short) NumberOptions.Octal))
return 8;
if (details.IsSet((short) NumberOptions.Binary))
return 2;
return 10;
}
private string GetDigits(CompoundTokenDetails details)
{
if (details.IsSet((short) NumberOptions.Hex))
return Strings.HexDigits;
if (details.IsSet((short) NumberOptions.Octal))
return Strings.OctalDigits;
if (details.IsSet((short) NumberOptions.Binary))
return Strings.BinaryDigits;
return Strings.DecimalDigits;
}
private int GetSafeWordLength(CompoundTokenDetails details)
{
if (details.IsSet((short) NumberOptions.Hex))
return 15;
if (details.IsSet((short) NumberOptions.Octal))
return 21; //maxWordLength 22
if (details.IsSet((short) NumberOptions.Binary))
return 63;
return 19; //maxWordLength 20
}
private int GetSectionCount(int stringLength, int safeWordLength)
{
var quotient = stringLength/safeWordLength;
var remainder = stringLength - quotient*safeWordLength;
return remainder == 0 ? quotient : quotient + 1;
}
//radix^safeWordLength
private ulong GetSafeWordRadix(CompoundTokenDetails details)
{
if (details.IsSet((short) NumberOptions.Hex))
return 1152921504606846976;
if (details.IsSet((short) NumberOptions.Octal))
return 9223372036854775808;
if (details.IsSet((short) NumberOptions.Binary))
return 9223372036854775808;
return 10000000000000000000;
}
private static bool IsIntegerCode(TypeCode code)
{
return (code >= TypeCode.SByte && code <= TypeCode.UInt64);
}
#endregion
} //class
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
internal sealed class PeWritingException : Exception
{
public PeWritingException(Exception inner)
: base(inner.Message, inner)
{ }
}
internal sealed class PeWriter
{
private const string ResourceSectionName = ".rsrc";
private const string RelocationSectionName = ".reloc";
/// <summary>
/// True if we should attempt to generate a deterministic output (no timestamps or random data).
/// </summary>
private readonly bool _deterministic;
private readonly int _timeStamp;
private readonly string _pdbPathOpt;
private readonly bool _is32bit;
private readonly ModulePropertiesForSerialization _properties;
private readonly IEnumerable<IWin32Resource> _nativeResourcesOpt;
private readonly ResourceSection _nativeResourceSectionOpt;
private readonly BlobBuilder _win32ResourceWriter = new BlobBuilder(1024);
private PeWriter(
ModulePropertiesForSerialization properties,
IEnumerable<IWin32Resource> nativeResourcesOpt,
ResourceSection nativeResourceSectionOpt,
string pdbPathOpt,
bool deterministic)
{
_properties = properties;
_pdbPathOpt = pdbPathOpt;
_deterministic = deterministic;
_nativeResourcesOpt = nativeResourcesOpt;
_nativeResourceSectionOpt = nativeResourceSectionOpt;
_is32bit = !_properties.Requires64bits;
// In the PE File Header this is a "Time/Date Stamp" whose description is "Time and date
// the file was created in seconds since January 1st 1970 00:00:00 or 0"
// However, when we want to make it deterministic we fill it in (later) with bits from the hash of the full PE file.
_timeStamp = _deterministic ? 0 : (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
}
private bool EmitPdb => _pdbPathOpt != null;
public static bool WritePeToStream(
EmitContext context,
CommonMessageProvider messageProvider,
Func<Stream> getPeStream,
Func<Stream> getPortablePdbStreamOpt,
PdbWriter nativePdbWriterOpt,
string pdbPathOpt,
bool allowMissingMethodBodies,
bool deterministic,
CancellationToken cancellationToken)
{
// If PDB writer is given, we have to have PDB path.
Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null);
var peWriter = new PeWriter(context.Module.Properties, context.Module.Win32Resources, context.Module.Win32ResourceSection, pdbPathOpt, deterministic);
var mdWriter = FullMetadataWriter.Create(context, messageProvider, allowMissingMethodBodies, deterministic, getPortablePdbStreamOpt != null, cancellationToken);
return peWriter.WritePeToStream(mdWriter, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt);
}
private bool WritePeToStream(MetadataWriter mdWriter, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt)
{
// TODO: we can precalculate the exact size of IL stream
var ilWriter = new BlobBuilder(32 * 1024);
var metadataWriter = new BlobBuilder(16 * 1024);
var mappedFieldDataWriter = new BlobBuilder();
var managedResourceWriter = new BlobBuilder(1024);
var debugMetadataWriterOpt = (getPortablePdbStreamOpt != null) ? new BlobBuilder(16 * 1024) : null;
nativePdbWriterOpt?.SetMetadataEmitter(mdWriter);
// Since we are producing a full assembly, we should not have a module version ID
// imposed ahead-of time. Instead we will compute a deterministic module version ID
// based on the contents of the generated stream.
Debug.Assert(_properties.PersistentIdentifier == default(Guid));
int sectionCount = 1;
if (_properties.RequiresStartupStub) sectionCount++; //.reloc
if (!IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt) || _nativeResourceSectionOpt != null) sectionCount++; //.rsrc;
int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount);
int textSectionRva = BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment);
int moduleVersionIdOffsetInMetadataStream;
int methodBodyStreamRva = textSectionRva + OffsetToILStream;
int entryPointToken;
MetadataSizes metadataSizes;
mdWriter.SerializeMetadataAndIL(
metadataWriter,
debugMetadataWriterOpt,
nativePdbWriterOpt,
ilWriter,
mappedFieldDataWriter,
managedResourceWriter,
methodBodyStreamRva,
mdSizes => CalculateMappedFieldDataStreamRva(textSectionRva, mdSizes),
out moduleVersionIdOffsetInMetadataStream,
out entryPointToken,
out metadataSizes);
ContentId nativePdbContentId;
if (nativePdbWriterOpt != null)
{
if (entryPointToken != 0)
{
nativePdbWriterOpt.SetEntryPoint((uint)entryPointToken);
}
var assembly = mdWriter.Module.AsAssembly;
if (assembly != null && assembly.Kind == OutputKind.WindowsRuntimeMetadata)
{
// Dev12: If compiling to winmdobj, we need to add to PDB source spans of
// all types and members for better error reporting by WinMDExp.
nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap());
}
else
{
#if DEBUG
// validate that all definitions are writable
// if same scenario would happen in an winmdobj project
nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap());
#endif
}
nativePdbContentId = nativePdbWriterOpt.GetContentId();
// the writer shall not be used after this point for writing:
nativePdbWriterOpt = null;
}
else
{
nativePdbContentId = default(ContentId);
}
// write to Portable PDB stream:
ContentId portablePdbContentId;
Stream portablePdbStream = getPortablePdbStreamOpt?.Invoke();
if (portablePdbStream != null)
{
debugMetadataWriterOpt.WriteContentTo(portablePdbStream);
if (_deterministic)
{
portablePdbContentId = ContentId.FromHash(CryptographicHashProvider.ComputeSha1(portablePdbStream));
}
else
{
portablePdbContentId = new ContentId(Guid.NewGuid().ToByteArray(), BitConverter.GetBytes(_timeStamp));
}
}
else
{
portablePdbContentId = default(ContentId);
}
// Only the size of the fixed part of the debug table goes here.
DirectoryEntry debugDirectory = default(DirectoryEntry);
DirectoryEntry importTable = default(DirectoryEntry);
DirectoryEntry importAddressTable = default(DirectoryEntry);
int entryPointAddress = 0;
if (EmitPdb)
{
debugDirectory = new DirectoryEntry(textSectionRva + ComputeOffsetToDebugTable(metadataSizes), ImageDebugDirectoryBaseSize);
}
if (_properties.RequiresStartupStub)
{
importAddressTable = new DirectoryEntry(textSectionRva, SizeOfImportAddressTable);
entryPointAddress = CalculateMappedFieldDataStreamRva(textSectionRva, metadataSizes) - (_is32bit ? 6 : 10); // TODO: constants
importTable = new DirectoryEntry(textSectionRva + ComputeOffsetToImportTable(metadataSizes), (_is32bit ? 66 : 70) + 13); // TODO: constants
}
var corHeaderDirectory = new DirectoryEntry(textSectionRva + SizeOfImportAddressTable, size: CorHeaderSize);
long ntHeaderTimestampPosition;
long metadataPosition;
List<SectionHeader> sectionHeaders = CreateSectionHeaders(metadataSizes, sectionCount);
CoffHeader coffHeader;
NtHeader ntHeader;
FillInNtHeader(sectionHeaders, entryPointAddress, corHeaderDirectory, importTable, importAddressTable, debugDirectory, out coffHeader, out ntHeader);
Stream peStream = getPeStream();
if (peStream == null)
{
return false;
}
WriteHeaders(peStream, ntHeader, coffHeader, sectionHeaders, out ntHeaderTimestampPosition);
WriteTextSection(
peStream,
sectionHeaders[0],
importTable.RelativeVirtualAddress,
importAddressTable.RelativeVirtualAddress,
entryPointToken,
metadataWriter,
ilWriter,
mappedFieldDataWriter,
managedResourceWriter,
metadataSizes,
nativePdbContentId,
portablePdbContentId,
out metadataPosition);
var resourceSection = sectionHeaders.FirstOrDefault(s => s.Name == ResourceSectionName);
if (resourceSection != null)
{
WriteResourceSection(peStream, resourceSection);
}
var relocSection = sectionHeaders.FirstOrDefault(s => s.Name == RelocationSectionName);
if (relocSection != null)
{
WriteRelocSection(peStream, relocSection, entryPointAddress);
}
if (_deterministic)
{
var mvidPosition = metadataPosition + moduleVersionIdOffsetInMetadataStream;
WriteDeterministicGuidAndTimestamps(peStream, mvidPosition, ntHeaderTimestampPosition);
}
return true;
}
private List<SectionHeader> CreateSectionHeaders(MetadataSizes metadataSizes, int sectionCount)
{
var sectionHeaders = new List<SectionHeader>();
SectionHeader lastSection;
int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount);
int sizeOfTextSection = ComputeSizeOfTextSection(metadataSizes);
sectionHeaders.Add(lastSection = new SectionHeader(
characteristics: SectionCharacteristics.MemRead |
SectionCharacteristics.MemExecute |
SectionCharacteristics.ContainsCode,
name: ".text",
numberOfLinenumbers: 0,
numberOfRelocations: 0,
pointerToLinenumbers: 0,
pointerToRawData: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.FileAlignment),
pointerToRelocations: 0,
relativeVirtualAddress: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment),
sizeOfRawData: BitArithmeticUtilities.Align(sizeOfTextSection, _properties.FileAlignment),
virtualSize: sizeOfTextSection
));
int resourcesRva = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment);
int sizeOfWin32Resources = this.ComputeSizeOfWin32Resources(resourcesRva);
if (sizeOfWin32Resources > 0)
{
sectionHeaders.Add(lastSection = new SectionHeader(
characteristics: SectionCharacteristics.MemRead |
SectionCharacteristics.ContainsInitializedData,
name: ResourceSectionName,
numberOfLinenumbers: 0,
numberOfRelocations: 0,
pointerToLinenumbers: 0,
pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData,
pointerToRelocations: 0,
relativeVirtualAddress: resourcesRva,
sizeOfRawData: BitArithmeticUtilities.Align(sizeOfWin32Resources, _properties.FileAlignment),
virtualSize: sizeOfWin32Resources
));
}
if (_properties.RequiresStartupStub)
{
var size = (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) ? 14 : 12; // TODO: constants
sectionHeaders.Add(lastSection = new SectionHeader(
characteristics: SectionCharacteristics.MemRead |
SectionCharacteristics.MemDiscardable |
SectionCharacteristics.ContainsInitializedData,
name: RelocationSectionName,
numberOfLinenumbers: 0,
numberOfRelocations: 0,
pointerToLinenumbers: 0,
pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData,
pointerToRelocations: 0,
relativeVirtualAddress: BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment),
sizeOfRawData: BitArithmeticUtilities.Align(size, _properties.FileAlignment),
virtualSize: size));
}
Debug.Assert(sectionHeaders.Count == sectionCount);
return sectionHeaders;
}
private const string CorEntryPointDll = "mscoree.dll";
private string CorEntryPointName => (_properties.ImageCharacteristics & Characteristics.Dll) != 0 ? "_CorDllMain" : "_CorExeMain";
private int SizeOfImportAddressTable => _properties.RequiresStartupStub ? (_is32bit ? 2 * sizeof(uint) : 2 * sizeof(ulong)) : 0;
// (_is32bit ? 66 : 70);
private int SizeOfImportTable =>
sizeof(uint) + // RVA
sizeof(uint) + // 0
sizeof(uint) + // 0
sizeof(uint) + // name RVA
sizeof(uint) + // import address table RVA
20 + // ?
(_is32bit ? 3 * sizeof(uint) : 2 * sizeof(ulong)) + // import lookup table
sizeof(ushort) + // hint
CorEntryPointName.Length +
1; // NUL
private static int SizeOfNameTable =>
CorEntryPointDll.Length + 1 + sizeof(ushort);
private int SizeOfRuntimeStartupStub => _is32bit ? 8 : 16;
private int CalculateOffsetToMappedFieldDataStream(MetadataSizes metadataSizes)
{
int result = ComputeOffsetToImportTable(metadataSizes);
if (_properties.RequiresStartupStub)
{
result += SizeOfImportTable + SizeOfNameTable;
result = BitArithmeticUtilities.Align(result, _is32bit ? 4 : 8); //optional padding to make startup stub's target address align on word or double word boundary
result += SizeOfRuntimeStartupStub;
}
return result;
}
private int CalculateMappedFieldDataStreamRva(int textSectionRva, MetadataSizes metadataSizes)
{
return textSectionRva + CalculateOffsetToMappedFieldDataStream(metadataSizes);
}
/// <summary>
/// Compute a deterministic Guid and timestamp based on the contents of the stream, and replace
/// the 16 zero bytes at the given position and one or two 4-byte values with that computed Guid and timestamp.
/// </summary>
/// <param name="peStream">PE stream.</param>
/// <param name="mvidPosition">Position in the stream of 16 zero bytes to be replaced by a Guid</param>
/// <param name="ntHeaderTimestampPosition">Position in the stream of four zero bytes to be replaced by a timestamp</param>
private static void WriteDeterministicGuidAndTimestamps(
Stream peStream,
long mvidPosition,
long ntHeaderTimestampPosition)
{
Debug.Assert(mvidPosition != 0);
Debug.Assert(ntHeaderTimestampPosition != 0);
var previousPosition = peStream.Position;
// Compute and write deterministic guid data over the relevant portion of the stream
peStream.Position = 0;
var contentId = ContentId.FromHash(CryptographicHashProvider.ComputeSha1(peStream));
// The existing Guid should be zero.
CheckZeroDataInStream(peStream, mvidPosition, contentId.Guid.Length);
peStream.Position = mvidPosition;
peStream.Write(contentId.Guid, 0, contentId.Guid.Length);
// The existing timestamp should be zero.
CheckZeroDataInStream(peStream, ntHeaderTimestampPosition, contentId.Stamp.Length);
peStream.Position = ntHeaderTimestampPosition;
peStream.Write(contentId.Stamp, 0, contentId.Stamp.Length);
peStream.Position = previousPosition;
}
[Conditional("DEBUG")]
private static void CheckZeroDataInStream(Stream stream, long position, int bytes)
{
stream.Position = position;
for (int i = 0; i < bytes; i++)
{
int value = stream.ReadByte();
Debug.Assert(value == 0);
}
}
private int ComputeOffsetToDebugTable(MetadataSizes metadataSizes)
{
Debug.Assert(metadataSizes.MetadataSize % 4 == 0);
Debug.Assert(metadataSizes.ResourceDataSize % 4 == 0);
return
ComputeOffsetToMetadata(metadataSizes.ILStreamSize) +
metadataSizes.MetadataSize +
metadataSizes.ResourceDataSize +
metadataSizes.StrongNameSignatureSize;
}
private int ComputeOffsetToImportTable(MetadataSizes metadataSizes)
{
return
ComputeOffsetToDebugTable(metadataSizes) +
ComputeSizeOfDebugDirectory();
}
private const int CorHeaderSize =
sizeof(int) + // header size
sizeof(short) + // major runtime version
sizeof(short) + // minor runtime version
sizeof(long) + // metadata directory
sizeof(int) + // COR flags
sizeof(int) + // entry point
sizeof(long) + // resources directory
sizeof(long) + // strong name signature directory
sizeof(long) + // code manager table directory
sizeof(long) + // vtable fixups directory
sizeof(long) + // export address table jumps directory
sizeof(long); // managed-native header directory
private int OffsetToILStream => SizeOfImportAddressTable + CorHeaderSize;
private int ComputeOffsetToMetadata(int ilStreamLength)
{
return OffsetToILStream + BitArithmeticUtilities.Align(ilStreamLength, 4);
}
private const int ImageDebugDirectoryBaseSize =
sizeof(uint) + // Characteristics
sizeof(uint) + // TimeDataStamp
sizeof(uint) + // Version
sizeof(uint) + // Type
sizeof(uint) + // SizeOfData
sizeof(uint) + // AddressOfRawData
sizeof(uint); // PointerToRawData
private int ComputeSizeOfDebugDirectoryData()
{
return
4 + // 4B signature "RSDS"
16 + // GUID
sizeof(uint) + // Age
Encoding.UTF8.GetByteCount(_pdbPathOpt) +
1; // Null terminator
}
private int ComputeSizeOfDebugDirectory()
{
return EmitPdb ? ImageDebugDirectoryBaseSize + ComputeSizeOfDebugDirectoryData() : 0;
}
private int ComputeSizeOfPeHeaders(int sectionCount)
{
int sizeOfPeHeaders = 128 + 4 + 20 + 224 + 40 * sectionCount; // TODO: constants
if (!_is32bit)
{
sizeOfPeHeaders += 16;
}
return sizeOfPeHeaders;
}
private int ComputeSizeOfTextSection(MetadataSizes metadataSizes)
{
Debug.Assert(metadataSizes.MappedFieldDataSize % MetadataWriter.MappedFieldDataAlignment == 0);
return CalculateOffsetToMappedFieldDataStream(metadataSizes) + metadataSizes.MappedFieldDataSize;
}
private int ComputeSizeOfWin32Resources(int resourcesRva)
{
this.SerializeWin32Resources(resourcesRva);
int result = 0;
if (_win32ResourceWriter.Count > 0)
{
result += BitArithmeticUtilities.Align(_win32ResourceWriter.Count, 4);
} // result += Align(this.win32ResourceWriter.Length+1, 8);
return result;
}
private CorHeader CreateCorHeader(MetadataSizes metadataSizes, int textSectionRva, int entryPointToken)
{
int metadataRva = textSectionRva + ComputeOffsetToMetadata(metadataSizes.ILStreamSize);
int resourcesRva = metadataRva + metadataSizes.MetadataSize;
int signatureRva = resourcesRva + metadataSizes.ResourceDataSize;
return new CorHeader(
entryPointTokenOrRelativeVirtualAddress: entryPointToken,
flags: _properties.GetCorHeaderFlags(),
metadataDirectory: new DirectoryEntry(metadataRva, metadataSizes.MetadataSize),
resourcesDirectory: new DirectoryEntry(resourcesRva, metadataSizes.ResourceDataSize),
strongNameSignatureDirectory: new DirectoryEntry(signatureRva, metadataSizes.StrongNameSignatureSize));
}
private void FillInNtHeader(
List<SectionHeader> sectionHeaders,
int entryPointAddress,
DirectoryEntry corHeader,
DirectoryEntry importTable,
DirectoryEntry importAddressTable,
DirectoryEntry debugTable,
out CoffHeader coffHeader,
out NtHeader ntHeader)
{
short sectionCount = (short)sectionHeaders.Count;
coffHeader = new CoffHeader(
machine: (_properties.Machine == 0) ? Machine.I386 : _properties.Machine,
numberOfSections: sectionCount,
timeDateStamp: _timeStamp,
pointerToSymbolTable: 0,
numberOfSymbols: 0,
sizeOfOptionalHeader: (short)(_is32bit ? 224 : 240), // TODO: constants
characteristics: _properties.ImageCharacteristics);
SectionHeader codeSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsCode) != 0);
SectionHeader dataSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0);
ntHeader = new NtHeader();
ntHeader.Magic = _is32bit ? PEMagic.PE32 : PEMagic.PE32Plus;
ntHeader.MajorLinkerVersion = _properties.LinkerMajorVersion;
ntHeader.MinorLinkerVersion = _properties.LinkerMinorVersion;
ntHeader.AddressOfEntryPoint = entryPointAddress;
ntHeader.BaseOfCode = codeSection?.RelativeVirtualAddress ?? 0;
ntHeader.BaseOfData = dataSection?.RelativeVirtualAddress ?? 0;
ntHeader.ImageBase = _properties.BaseAddress;
ntHeader.FileAlignment = _properties.FileAlignment;
ntHeader.MajorSubsystemVersion = _properties.MajorSubsystemVersion;
ntHeader.MinorSubsystemVersion = _properties.MinorSubsystemVersion;
ntHeader.Subsystem = _properties.Subsystem;
ntHeader.DllCharacteristics = _properties.DllCharacteristics;
ntHeader.SizeOfStackReserve = _properties.SizeOfStackReserve;
ntHeader.SizeOfStackCommit = _properties.SizeOfStackCommit;
ntHeader.SizeOfHeapReserve = _properties.SizeOfHeapReserve;
ntHeader.SizeOfHeapCommit = _properties.SizeOfHeapCommit;
ntHeader.SizeOfCode = codeSection?.SizeOfRawData ?? 0;
ntHeader.SizeOfInitializedData = sectionHeaders.Sum(
sectionHeader => (sectionHeader.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0 ? sectionHeader.SizeOfRawData : 0);
ntHeader.SizeOfHeaders = BitArithmeticUtilities.Align(ComputeSizeOfPeHeaders(sectionCount), _properties.FileAlignment);
var lastSection = sectionHeaders.Last();
ntHeader.SizeOfImage = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment);
ntHeader.SizeOfUninitializedData = 0;
ntHeader.ImportAddressTable = importAddressTable;
ntHeader.CliHeaderTable = corHeader;
ntHeader.ImportTable = importTable;
var relocSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == RelocationSectionName);
if (relocSection != null)
{
ntHeader.BaseRelocationTable = new DirectoryEntry(relocSection.RelativeVirtualAddress, relocSection.VirtualSize);
}
ntHeader.DebugTable = debugTable;
var resourceSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == ResourceSectionName);
if (resourceSection != null)
{
ntHeader.ResourceTable = new DirectoryEntry(resourceSection.RelativeVirtualAddress, resourceSection.VirtualSize);
}
}
////
//// Resource Format.
////
////
//// Resource directory consists of two counts, following by a variable length
//// array of directory entries. The first count is the number of entries at
//// beginning of the array that have actual names associated with each entry.
//// The entries are in ascending order, case insensitive strings. The second
//// count is the number of entries that immediately follow the named entries.
//// This second count identifies the number of entries that have 16-bit integer
//// Ids as their name. These entries are also sorted in ascending order.
////
//// This structure allows fast lookup by either name or number, but for any
//// given resource entry only one form of lookup is supported, not both.
//// This is consistent with the syntax of the .RC file and the .RES file.
////
//typedef struct _IMAGE_RESOURCE_DIRECTORY {
// DWORD Characteristics;
// DWORD TimeDateStamp;
// WORD MajorVersion;
// WORD MinorVersion;
// WORD NumberOfNamedEntries;
// WORD NumberOfIdEntries;
//// IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[];
//} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;
//#define IMAGE_RESOURCE_NAME_IS_STRING 0x80000000
//#define IMAGE_RESOURCE_DATA_IS_DIRECTORY 0x80000000
////
//// Each directory contains the 32-bit Name of the entry and an offset,
//// relative to the beginning of the resource directory of the data associated
//// with this directory entry. If the name of the entry is an actual text
//// string instead of an integer Id, then the high order bit of the name field
//// is set to one and the low order 31-bits are an offset, relative to the
//// beginning of the resource directory of the string, which is of type
//// IMAGE_RESOURCE_DIRECTORY_STRING. Otherwise the high bit is clear and the
//// low-order 16-bits are the integer Id that identify this resource directory
//// entry. If the directory entry is yet another resource directory (i.e. a
//// subdirectory), then the high order bit of the offset field will be
//// set to indicate this. Otherwise the high bit is clear and the offset
//// field points to a resource data entry.
////
//typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {
// union {
// struct {
// DWORD NameOffset:31;
// DWORD NameIsString:1;
// } DUMMYSTRUCTNAME;
// DWORD Name;
// WORD Id;
// } DUMMYUNIONNAME;
// union {
// DWORD OffsetToData;
// struct {
// DWORD OffsetToDirectory:31;
// DWORD DataIsDirectory:1;
// } DUMMYSTRUCTNAME2;
// } DUMMYUNIONNAME2;
//} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY;
////
//// For resource directory entries that have actual string names, the Name
//// field of the directory entry points to an object of the following type.
//// All of these string objects are stored together after the last resource
//// directory entry and before the first resource data object. This minimizes
//// the impact of these variable length objects on the alignment of the fixed
//// size directory entry objects.
////
//typedef struct _IMAGE_RESOURCE_DIRECTORY_STRING {
// WORD Length;
// CHAR NameString[ 1 ];
//} IMAGE_RESOURCE_DIRECTORY_STRING, *PIMAGE_RESOURCE_DIRECTORY_STRING;
//typedef struct _IMAGE_RESOURCE_DIR_STRING_U {
// WORD Length;
// WCHAR NameString[ 1 ];
//} IMAGE_RESOURCE_DIR_STRING_U, *PIMAGE_RESOURCE_DIR_STRING_U;
////
//// Each resource data entry describes a leaf node in the resource directory
//// tree. It contains an offset, relative to the beginning of the resource
//// directory of the data for the resource, a size field that gives the number
//// of bytes of data at that offset, a CodePage that should be used when
//// decoding code point values within the resource data. Typically for new
//// applications the code page would be the unicode code page.
////
//typedef struct _IMAGE_RESOURCE_DATA_ENTRY {
// DWORD OffsetToData;
// DWORD Size;
// DWORD CodePage;
// DWORD Reserved;
//} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY;
private class Directory
{
internal readonly string Name;
internal readonly int ID;
internal ushort NumberOfNamedEntries;
internal ushort NumberOfIdEntries;
internal readonly List<object> Entries;
internal Directory(string name, int id)
{
this.Name = name;
this.ID = id;
this.Entries = new List<object>();
}
}
private static int CompareResources(IWin32Resource left, IWin32Resource right)
{
int result = CompareResourceIdentifiers(left.TypeId, left.TypeName, right.TypeId, right.TypeName);
return (result == 0) ? CompareResourceIdentifiers(left.Id, left.Name, right.Id, right.Name) : result;
}
//when comparing a string vs ordinal, the string should always be less than the ordinal. Per the spec,
//entries identified by string must precede those identified by ordinal.
private static int CompareResourceIdentifiers(int xOrdinal, string xString, int yOrdinal, string yString)
{
if (xString == null)
{
if (yString == null)
{
return xOrdinal - yOrdinal;
}
else
{
return 1;
}
}
else if (yString == null)
{
return -1;
}
else
{
return String.Compare(xString, yString, StringComparison.OrdinalIgnoreCase);
}
}
//sort the resources by ID least to greatest then by NAME.
//Where strings and ordinals are compared, strings are less than ordinals.
internal static IEnumerable<IWin32Resource> SortResources(IEnumerable<IWin32Resource> resources)
{
return resources.OrderBy(CompareResources);
}
//Win32 resources are supplied to the compiler in one of two forms, .RES (the output of the resource compiler),
//or .OBJ (the output of running cvtres.exe on a .RES file). A .RES file is parsed and processed into
//a set of objects implementing IWin32Resources. These are then ordered and the final image form is constructed
//and written to the resource section. Resources in .OBJ form are already very close to their final output
//form. Rather than reading them and parsing them into a set of objects similar to those produced by
//processing a .RES file, we process them like the native linker would, copy the relevant sections from
//the .OBJ into our output and apply some fixups.
private void SerializeWin32Resources(int resourcesRva)
{
if (_nativeResourceSectionOpt != null)
{
SerializeWin32Resources(_nativeResourceSectionOpt, resourcesRva);
return;
}
if (IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt))
{
return;
}
SerializeWin32Resources(_nativeResourcesOpt, resourcesRva);
}
private void SerializeWin32Resources(IEnumerable<IWin32Resource> theResources, int resourcesRva)
{
theResources = SortResources(theResources);
Directory typeDirectory = new Directory(string.Empty, 0);
Directory nameDirectory = null;
Directory languageDirectory = null;
int lastTypeID = int.MinValue;
string lastTypeName = null;
int lastID = int.MinValue;
string lastName = null;
uint sizeOfDirectoryTree = 16;
//EDMAURER note that this list is assumed to be sorted lowest to highest
//first by typeId, then by Id.
foreach (IWin32Resource r in theResources)
{
bool typeDifferent = (r.TypeId < 0 && r.TypeName != lastTypeName) || r.TypeId > lastTypeID;
if (typeDifferent)
{
lastTypeID = r.TypeId;
lastTypeName = r.TypeName;
if (lastTypeID < 0)
{
Debug.Assert(typeDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with types encoded as strings precede those encoded as ints");
typeDirectory.NumberOfNamedEntries++;
}
else
{
typeDirectory.NumberOfIdEntries++;
}
sizeOfDirectoryTree += 24;
typeDirectory.Entries.Add(nameDirectory = new Directory(lastTypeName, lastTypeID));
}
if (typeDifferent || (r.Id < 0 && r.Name != lastName) || r.Id > lastID)
{
lastID = r.Id;
lastName = r.Name;
if (lastID < 0)
{
Debug.Assert(nameDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with names encoded as strings precede those encoded as ints");
nameDirectory.NumberOfNamedEntries++;
}
else
{
nameDirectory.NumberOfIdEntries++;
}
sizeOfDirectoryTree += 24;
nameDirectory.Entries.Add(languageDirectory = new Directory(lastName, lastID));
}
languageDirectory.NumberOfIdEntries++;
sizeOfDirectoryTree += 8;
languageDirectory.Entries.Add(r);
}
var dataWriter = new BlobBuilder();
//'dataWriter' is where opaque resource data goes as well as strings that are used as type or name identifiers
this.WriteDirectory(typeDirectory, _win32ResourceWriter, 0, 0, sizeOfDirectoryTree, resourcesRva, dataWriter);
_win32ResourceWriter.LinkSuffix(dataWriter);
_win32ResourceWriter.WriteByte(0);
while ((_win32ResourceWriter.Count % 4) != 0)
{
_win32ResourceWriter.WriteByte(0);
}
}
private void WriteDirectory(Directory directory, BlobBuilder writer, uint offset, uint level, uint sizeOfDirectoryTree, int virtualAddressBase, BlobBuilder dataWriter)
{
writer.WriteUInt32(0); // Characteristics
writer.WriteUInt32(0); // Timestamp
writer.WriteUInt32(0); // Version
writer.WriteUInt16(directory.NumberOfNamedEntries);
writer.WriteUInt16(directory.NumberOfIdEntries);
uint n = (uint)directory.Entries.Count;
uint k = offset + 16 + n * 8;
for (int i = 0; i < n; i++)
{
int id;
string name;
uint nameOffset = (uint)dataWriter.Position + sizeOfDirectoryTree;
uint directoryOffset = k;
Directory subDir = directory.Entries[i] as Directory;
if (subDir != null)
{
id = subDir.ID;
name = subDir.Name;
if (level == 0)
{
k += SizeOfDirectory(subDir);
}
else
{
k += 16 + 8 * (uint)subDir.Entries.Count;
}
}
else
{
//EDMAURER write out an IMAGE_RESOURCE_DATA_ENTRY followed
//immediately by the data that it refers to. This results
//in a layout different than that produced by pulling the resources
//from an OBJ. In that case all of the data bits of a resource are
//contiguous in .rsrc$02. After processing these will end up at
//the end of .rsrc following all of the directory
//info and IMAGE_RESOURCE_DATA_ENTRYs
IWin32Resource r = (IWin32Resource)directory.Entries[i];
id = level == 0 ? r.TypeId : level == 1 ? r.Id : (int)r.LanguageId;
name = level == 0 ? r.TypeName : level == 1 ? r.Name : null;
dataWriter.WriteUInt32((uint)(virtualAddressBase + sizeOfDirectoryTree + 16 + dataWriter.Position));
byte[] data = new List<byte>(r.Data).ToArray();
dataWriter.WriteUInt32((uint)data.Length);
dataWriter.WriteUInt32(r.CodePage);
dataWriter.WriteUInt32(0);
dataWriter.WriteBytes(data);
while ((dataWriter.Count % 4) != 0)
{
dataWriter.WriteByte(0);
}
}
if (id >= 0)
{
writer.WriteInt32(id);
}
else
{
if (name == null)
{
name = string.Empty;
}
writer.WriteUInt32(nameOffset | 0x80000000);
dataWriter.WriteUInt16((ushort)name.Length);
dataWriter.WriteUTF16(name);
}
if (subDir != null)
{
writer.WriteUInt32(directoryOffset | 0x80000000);
}
else
{
writer.WriteUInt32(nameOffset);
}
}
k = offset + 16 + n * 8;
for (int i = 0; i < n; i++)
{
Directory subDir = directory.Entries[i] as Directory;
if (subDir != null)
{
this.WriteDirectory(subDir, writer, k, level + 1, sizeOfDirectoryTree, virtualAddressBase, dataWriter);
if (level == 0)
{
k += SizeOfDirectory(subDir);
}
else
{
k += 16 + 8 * (uint)subDir.Entries.Count;
}
}
}
}
private static uint SizeOfDirectory(Directory/*!*/ directory)
{
uint n = (uint)directory.Entries.Count;
uint size = 16 + 8 * n;
for (int i = 0; i < n; i++)
{
Directory subDir = directory.Entries[i] as Directory;
if (subDir != null)
{
size += 16 + 8 * (uint)subDir.Entries.Count;
}
}
return size;
}
private void SerializeWin32Resources(ResourceSection resourceSections, int resourcesRva)
{
var sectionWriter = _win32ResourceWriter.ReserveBytes(resourceSections.SectionBytes.Length);
sectionWriter.WriteBytes(resourceSections.SectionBytes);
var readStream = new MemoryStream(resourceSections.SectionBytes);
var reader = new BinaryReader(readStream);
foreach (int addressToFixup in resourceSections.Relocations)
{
sectionWriter.Offset = addressToFixup;
reader.BaseStream.Position = addressToFixup;
sectionWriter.WriteUInt32(reader.ReadUInt32() + (uint)resourcesRva);
}
}
//#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file.
//#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // File is executable (i.e. no unresolved external references).
//#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line numbers stripped from file.
//#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // Local symbols stripped from file.
//#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010 // Aggressively trim working set
//#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // App can handle >2gb addresses
//#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // Bytes of machine word are reversed.
//#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine.
//#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // Debugging info stripped from file in .DBG file
//#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // If Image is on removable media, copy and run from the swap file.
//#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // If Image is on Net, copy and run from the swap file.
//#define IMAGE_FILE_SYSTEM 0x1000 // System File.
//#define IMAGE_FILE_DLL 0x2000 // File is a DLL.
//#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // File should only be run on a UP machine
//#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // Bytes of machine word are reversed.
private static readonly byte[] s_dosHeader = new byte[]
{
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd,
0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e,
0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
private void WriteHeaders(Stream peStream, NtHeader ntHeader, CoffHeader coffHeader, List<SectionHeader> sectionHeaders, out long ntHeaderTimestampPosition)
{
var writer = PooledBlobBuilder.GetInstance();
// MS-DOS stub (128 bytes)
writer.WriteBytes(s_dosHeader);
// PE Signature "PE\0\0"
writer.WriteUInt32(0x00004550);
// COFF Header (20 bytes)
writer.WriteUInt16((ushort)coffHeader.Machine);
writer.WriteUInt16((ushort)coffHeader.NumberOfSections);
ntHeaderTimestampPosition = writer.Position + peStream.Position;
writer.WriteUInt32((uint)coffHeader.TimeDateStamp);
writer.WriteUInt32((uint)coffHeader.PointerToSymbolTable);
writer.WriteUInt32((uint)coffHeader.NumberOfSymbols);
writer.WriteUInt16((ushort)(_is32bit ? 224 : 240)); // SizeOfOptionalHeader
writer.WriteUInt16((ushort)coffHeader.Characteristics);
// PE Headers:
writer.WriteUInt16((ushort)(_is32bit ? PEMagic.PE32 : PEMagic.PE32Plus)); // 2
writer.WriteByte(ntHeader.MajorLinkerVersion); // 3
writer.WriteByte(ntHeader.MinorLinkerVersion); // 4
writer.WriteUInt32((uint)ntHeader.SizeOfCode); // 8
writer.WriteUInt32((uint)ntHeader.SizeOfInitializedData); // 12
writer.WriteUInt32((uint)ntHeader.SizeOfUninitializedData); // 16
writer.WriteUInt32((uint)ntHeader.AddressOfEntryPoint); // 20
writer.WriteUInt32((uint)ntHeader.BaseOfCode); // 24
if (_is32bit)
{
writer.WriteUInt32((uint)ntHeader.BaseOfData); // 28
writer.WriteUInt32((uint)ntHeader.ImageBase); // 32
}
else
{
writer.WriteUInt64(ntHeader.ImageBase); // 32
}
// NT additional fields:
writer.WriteUInt32((uint)ntHeader.SectionAlignment); // 36
writer.WriteUInt32((uint)ntHeader.FileAlignment); // 40
writer.WriteUInt16(ntHeader.MajorOperatingSystemVersion); // 42
writer.WriteUInt16(ntHeader.MinorOperatingSystemVersion); // 44
writer.WriteUInt16(ntHeader.MajorImageVersion); // 46
writer.WriteUInt16(ntHeader.MinorImageVersion); // 48
writer.WriteUInt16(ntHeader.MajorSubsystemVersion); // MajorSubsystemVersion 50
writer.WriteUInt16(ntHeader.MinorSubsystemVersion); // MinorSubsystemVersion 52
// Win32VersionValue (reserved, should be 0)
writer.WriteUInt32(0); // 56
writer.WriteUInt32((uint)ntHeader.SizeOfImage); // 60
writer.WriteUInt32((uint)ntHeader.SizeOfHeaders); // 64
writer.WriteUInt32(ntHeader.Checksum); // 68
writer.WriteUInt16((ushort)ntHeader.Subsystem); // 70
writer.WriteUInt16((ushort)ntHeader.DllCharacteristics);
if (_is32bit)
{
writer.WriteUInt32((uint)ntHeader.SizeOfStackReserve); // 76
writer.WriteUInt32((uint)ntHeader.SizeOfStackCommit); // 80
writer.WriteUInt32((uint)ntHeader.SizeOfHeapReserve); // 84
writer.WriteUInt32((uint)ntHeader.SizeOfHeapCommit); // 88
}
else
{
writer.WriteUInt64(ntHeader.SizeOfStackReserve); // 80
writer.WriteUInt64(ntHeader.SizeOfStackCommit); // 88
writer.WriteUInt64(ntHeader.SizeOfHeapReserve); // 96
writer.WriteUInt64(ntHeader.SizeOfHeapCommit); // 104
}
// LoaderFlags
writer.WriteUInt32(0); // 92|108
// The number of data-directory entries in the remainder of the header.
writer.WriteUInt32(16); // 96|112
// directory entries:
writer.WriteUInt32((uint)ntHeader.ExportTable.RelativeVirtualAddress); // 100|116
writer.WriteUInt32((uint)ntHeader.ExportTable.Size); // 104|120
writer.WriteUInt32((uint)ntHeader.ImportTable.RelativeVirtualAddress); // 108|124
writer.WriteUInt32((uint)ntHeader.ImportTable.Size); // 112|128
writer.WriteUInt32((uint)ntHeader.ResourceTable.RelativeVirtualAddress); // 116|132
writer.WriteUInt32((uint)ntHeader.ResourceTable.Size); // 120|136
writer.WriteUInt32((uint)ntHeader.ExceptionTable.RelativeVirtualAddress); // 124|140
writer.WriteUInt32((uint)ntHeader.ExceptionTable.Size); // 128|144
writer.WriteUInt32((uint)ntHeader.CertificateTable.RelativeVirtualAddress); // 132|148
writer.WriteUInt32((uint)ntHeader.CertificateTable.Size); // 136|152
writer.WriteUInt32((uint)ntHeader.BaseRelocationTable.RelativeVirtualAddress); // 140|156
writer.WriteUInt32((uint)ntHeader.BaseRelocationTable.Size); // 144|160
writer.WriteUInt32((uint)ntHeader.DebugTable.RelativeVirtualAddress); // 148|164
writer.WriteUInt32((uint)ntHeader.DebugTable.Size); // 152|168
writer.WriteUInt32((uint)ntHeader.CopyrightTable.RelativeVirtualAddress); // 156|172
writer.WriteUInt32((uint)ntHeader.CopyrightTable.Size); // 160|176
writer.WriteUInt32((uint)ntHeader.GlobalPointerTable.RelativeVirtualAddress); // 164|180
writer.WriteUInt32((uint)ntHeader.GlobalPointerTable.Size); // 168|184
writer.WriteUInt32((uint)ntHeader.ThreadLocalStorageTable.RelativeVirtualAddress); // 172|188
writer.WriteUInt32((uint)ntHeader.ThreadLocalStorageTable.Size); // 176|192
writer.WriteUInt32((uint)ntHeader.LoadConfigTable.RelativeVirtualAddress); // 180|196
writer.WriteUInt32((uint)ntHeader.LoadConfigTable.Size); // 184|200
writer.WriteUInt32((uint)ntHeader.BoundImportTable.RelativeVirtualAddress); // 188|204
writer.WriteUInt32((uint)ntHeader.BoundImportTable.Size); // 192|208
writer.WriteUInt32((uint)ntHeader.ImportAddressTable.RelativeVirtualAddress); // 196|212
writer.WriteUInt32((uint)ntHeader.ImportAddressTable.Size); // 200|216
writer.WriteUInt32((uint)ntHeader.DelayImportTable.RelativeVirtualAddress); // 204|220
writer.WriteUInt32((uint)ntHeader.DelayImportTable.Size); // 208|224
writer.WriteUInt32((uint)ntHeader.CliHeaderTable.RelativeVirtualAddress); // 212|228
writer.WriteUInt32((uint)ntHeader.CliHeaderTable.Size); // 216|232
writer.WriteUInt64(0); // 224|240
// Section Headers
foreach (var sectionHeader in sectionHeaders)
{
WriteSectionHeader(sectionHeader, writer);
}
writer.WriteContentTo(peStream);
writer.Free();
}
private static void WriteSectionHeader(SectionHeader sectionHeader, BlobBuilder writer)
{
if (sectionHeader.VirtualSize == 0)
{
return;
}
for (int j = 0, m = sectionHeader.Name.Length; j < 8; j++)
{
if (j < m)
{
writer.WriteByte((byte)sectionHeader.Name[j]);
}
else
{
writer.WriteByte(0);
}
}
writer.WriteUInt32((uint)sectionHeader.VirtualSize);
writer.WriteUInt32((uint)sectionHeader.RelativeVirtualAddress);
writer.WriteUInt32((uint)sectionHeader.SizeOfRawData);
writer.WriteUInt32((uint)sectionHeader.PointerToRawData);
writer.WriteUInt32((uint)sectionHeader.PointerToRelocations);
writer.WriteUInt32((uint)sectionHeader.PointerToLinenumbers);
writer.WriteUInt16(sectionHeader.NumberOfRelocations);
writer.WriteUInt16(sectionHeader.NumberOfLinenumbers);
writer.WriteUInt32((uint)sectionHeader.Characteristics);
}
private void WriteTextSection(
Stream peStream,
SectionHeader textSection,
int importTableRva,
int importAddressTableRva,
int entryPointToken,
BlobBuilder metadataWriter,
BlobBuilder ilWriter,
BlobBuilder mappedFieldDataWriter,
BlobBuilder managedResourceWriter,
MetadataSizes metadataSizes,
ContentId nativePdbContentId,
ContentId portablePdbContentId,
out long metadataPosition)
{
// TODO: zero out all bytes:
peStream.Position = textSection.PointerToRawData;
if (_properties.RequiresStartupStub)
{
WriteImportAddressTable(peStream, importTableRva);
}
var corHeader = CreateCorHeader(metadataSizes, textSection.RelativeVirtualAddress, entryPointToken);
WriteCorHeader(peStream, corHeader);
// IL:
ilWriter.Align(4);
ilWriter.WriteContentTo(peStream);
// metadata:
metadataPosition = peStream.Position;
Debug.Assert(metadataWriter.Count % 4 == 0);
metadataWriter.WriteContentTo(peStream);
// managed resources:
Debug.Assert(managedResourceWriter.Count % 4 == 0);
managedResourceWriter.WriteContentTo(peStream);
// strong name signature:
WriteSpaceForHash(peStream, metadataSizes.StrongNameSignatureSize);
if (EmitPdb)
{
WriteDebugTable(peStream, textSection, nativePdbContentId, portablePdbContentId, metadataSizes);
}
if (_properties.RequiresStartupStub)
{
WriteImportTable(peStream, importTableRva, importAddressTableRva);
WriteNameTable(peStream);
WriteRuntimeStartupStub(peStream, importAddressTableRva);
}
// mapped field data:
mappedFieldDataWriter.WriteContentTo(peStream);
// TODO: zero out all bytes:
int alignedPosition = textSection.PointerToRawData + textSection.SizeOfRawData;
if (peStream.Position != alignedPosition)
{
peStream.Position = alignedPosition - 1;
peStream.WriteByte(0);
}
}
private void WriteImportAddressTable(Stream peStream, int importTableRva)
{
var writer = new BlobBuilder(SizeOfImportAddressTable);
int ilRVA = importTableRva + 40;
int hintRva = ilRVA + (_is32bit ? 12 : 16);
// Import Address Table
if (_is32bit)
{
writer.WriteUInt32((uint)hintRva); // 4
writer.WriteUInt32(0); // 8
}
else
{
writer.WriteUInt64((uint)hintRva); // 8
writer.WriteUInt64(0); // 16
}
Debug.Assert(writer.Count == SizeOfImportAddressTable);
writer.WriteContentTo(peStream);
}
private void WriteImportTable(Stream peStream, int importTableRva, int importAddressTableRva)
{
var writer = new BlobBuilder(SizeOfImportTable);
int ilRVA = importTableRva + 40;
int hintRva = ilRVA + (_is32bit ? 12 : 16);
int nameRva = hintRva + 12 + 2;
// Import table
writer.WriteUInt32((uint)ilRVA); // 4
writer.WriteUInt32(0); // 8
writer.WriteUInt32(0); // 12
writer.WriteUInt32((uint)nameRva); // 16
writer.WriteUInt32((uint)importAddressTableRva); // 20
writer.WriteBytes(0, 20); // 40
// Import Lookup table
if (_is32bit)
{
writer.WriteUInt32((uint)hintRva); // 44
writer.WriteUInt32(0); // 48
writer.WriteUInt32(0); // 52
}
else
{
writer.WriteUInt64((uint)hintRva); // 48
writer.WriteUInt64(0); // 56
}
// Hint table
writer.WriteUInt16(0); // Hint 54|58
foreach (char ch in CorEntryPointName)
{
writer.WriteByte((byte)ch); // 65|69
}
writer.WriteByte(0); // 66|70
Debug.Assert(writer.Count == SizeOfImportTable);
writer.WriteContentTo(peStream);
}
private static void WriteNameTable(Stream peStream)
{
var writer = new BlobBuilder(SizeOfNameTable);
foreach (char ch in CorEntryPointDll)
{
writer.WriteByte((byte)ch);
}
writer.WriteByte(0);
writer.WriteUInt16(0);
Debug.Assert(writer.Count == SizeOfNameTable);
writer.WriteContentTo(peStream);
}
private static void WriteCorHeader(Stream peStream, CorHeader corHeader)
{
var writer = new BlobBuilder(CorHeaderSize);
writer.WriteUInt32(CorHeaderSize);
writer.WriteUInt16(corHeader.MajorRuntimeVersion);
writer.WriteUInt16(corHeader.MinorRuntimeVersion);
writer.WriteUInt32((uint)corHeader.MetadataDirectory.RelativeVirtualAddress);
writer.WriteUInt32((uint)corHeader.MetadataDirectory.Size);
writer.WriteUInt32((uint)corHeader.Flags);
writer.WriteUInt32((uint)corHeader.EntryPointTokenOrRelativeVirtualAddress);
writer.WriteUInt32((uint)(corHeader.ResourcesDirectory.Size == 0 ? 0 : corHeader.ResourcesDirectory.RelativeVirtualAddress)); // 28
writer.WriteUInt32((uint)corHeader.ResourcesDirectory.Size);
writer.WriteUInt32((uint)(corHeader.StrongNameSignatureDirectory.Size == 0 ? 0 : corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress)); // 36
writer.WriteUInt32((uint)corHeader.StrongNameSignatureDirectory.Size);
writer.WriteUInt32((uint)corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
writer.WriteUInt32((uint)corHeader.CodeManagerTableDirectory.Size);
writer.WriteUInt32((uint)corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
writer.WriteUInt32((uint)corHeader.VtableFixupsDirectory.Size);
writer.WriteUInt32((uint)corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
writer.WriteUInt32((uint)corHeader.ExportAddressTableJumpsDirectory.Size);
writer.WriteUInt64(0);
Debug.Assert(writer.Count == CorHeaderSize);
Debug.Assert(writer.Count % 4 == 0);
writer.WriteContentTo(peStream);
}
private static void WriteSpaceForHash(Stream peStream, int strongNameSignatureSize)
{
while (strongNameSignatureSize > 0)
{
peStream.WriteByte(0);
strongNameSignatureSize--;
}
}
private void WriteDebugTable(Stream peStream, SectionHeader textSection, ContentId nativePdbContentId, ContentId portablePdbContentId, MetadataSizes metadataSizes)
{
Debug.Assert(nativePdbContentId.IsDefault ^ portablePdbContentId.IsDefault);
var writer = PooledBlobBuilder.GetInstance();
// characteristics:
writer.WriteUInt32(0);
// PDB stamp & version
if (portablePdbContentId.IsDefault)
{
writer.WriteBytes(nativePdbContentId.Stamp);
writer.WriteUInt32(0);
}
else
{
writer.WriteBytes(portablePdbContentId.Stamp);
writer.WriteUInt32('P' << 24 | 'M' << 16 | 0x00 << 8 | 0x01);
}
// type:
const int ImageDebugTypeCodeView = 2;
writer.WriteUInt32(ImageDebugTypeCodeView);
// size of data:
writer.WriteUInt32((uint)ComputeSizeOfDebugDirectoryData());
uint dataOffset = (uint)ComputeOffsetToDebugTable(metadataSizes) + ImageDebugDirectoryBaseSize;
// PointerToRawData (RVA of the data):
writer.WriteUInt32((uint)textSection.RelativeVirtualAddress + dataOffset);
// AddressOfRawData (position of the data in the PE stream):
writer.WriteUInt32((uint)textSection.PointerToRawData + dataOffset);
writer.WriteByte((byte)'R');
writer.WriteByte((byte)'S');
writer.WriteByte((byte)'D');
writer.WriteByte((byte)'S');
// PDB id:
writer.WriteBytes(nativePdbContentId.Guid ?? portablePdbContentId.Guid);
// age
writer.WriteUInt32(PdbWriter.Age);
// UTF-8 encoded zero-terminated path to PDB
writer.WriteUTF8(_pdbPathOpt, allowUnpairedSurrogates: true);
writer.WriteByte(0);
writer.WriteContentTo(peStream);
writer.Free();
}
private void WriteRuntimeStartupStub(Stream peStream, int importAddressTableRva)
{
var writer = new BlobBuilder(16);
// entry point code, consisting of a jump indirect to _CorXXXMain
if (_is32bit)
{
//emit 0's (nops) to pad the entry point code so that the target address is aligned on a 4 byte boundary.
for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 4) - peStream.Position); i < n; i++)
{
writer.WriteByte(0);
}
writer.WriteUInt16(0);
writer.WriteByte(0xff);
writer.WriteByte(0x25); //4
writer.WriteUInt32((uint)importAddressTableRva + (uint)_properties.BaseAddress); //8
}
else
{
//emit 0's (nops) to pad the entry point code so that the target address is aligned on a 8 byte boundary.
for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 8) - peStream.Position); i < n; i++)
{
writer.WriteByte(0);
}
writer.WriteUInt32(0);
writer.WriteUInt16(0);
writer.WriteByte(0xff);
writer.WriteByte(0x25); //8
writer.WriteUInt64((ulong)importAddressTableRva + _properties.BaseAddress); //16
}
writer.WriteContentTo(peStream);
}
private void WriteRelocSection(Stream peStream, SectionHeader relocSection, int entryPointAddress)
{
peStream.Position = relocSection.PointerToRawData;
var writer = new BlobBuilder(relocSection.SizeOfRawData);
writer.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000);
writer.WriteUInt32(_properties.Requires64bits && !_properties.RequiresAmdInstructionSet ? 14u : 12u);
uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000;
uint relocType = _properties.Requires64bits ? 10u : 3u;
ushort s = (ushort)((relocType << 12) | offsetWithinPage);
writer.WriteUInt16(s);
if (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet)
{
writer.WriteUInt32(relocType << 12);
}
writer.WriteUInt16(0); // next chunk's RVA
writer.PadTo(relocSection.SizeOfRawData);
writer.WriteContentTo(peStream);
}
private void WriteResourceSection(Stream peStream, SectionHeader resourceSection)
{
peStream.Position = resourceSection.PointerToRawData;
_win32ResourceWriter.PadTo(resourceSection.SizeOfRawData);
_win32ResourceWriter.WriteContentTo(peStream);
}
}
}
| |
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 openCaseMaster.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;
}
}
}
| |
//-----------------------------------------------------------------------------
// Logicking's Game Factory
// Copyright (C) Logicking.com, Inc.
//-----------------------------------------------------------------------------
// Sample rag dolls for bullet
//-----------------------------------------------------------------------------
//shape $ShapeType::Box,$ShapeType::Sphere, $ShapeType::Capsule - 2
//joint $JointType::ConeTwist, $JointType::Hinge, $JointType::Dof6", $JointType::BallSocket"
datablock RagDollData(SpaceOrcRagDoll)
{
category = "RigidBody";
shapeFile = "art/shapes/actors/SpaceOrc/SpaceOrc.dts";
minContactSpeed = 5.0;
slidingThreshold = 0.5;
collisionSoundsCount = 1;
collisionSound[0] = bodyFall0;
//pelvis
boneNodeName[0] = "Bip01 Pelvis";
boneSize[0] = "0.4 0.1 0.0";
boneMass[0] = 2;
boneShape[0] = $ShapeType::Capsule;
boneOffset[0] = "0 0 0";
//torso
boneParentNodeName[1] = "Bip01 Pelvis";
boneNodeName[1] = "Bip01 Spine2";
boneSize[1] = "0.2 0.2 0.0";
boneMass[1] = 2;
boneShape[1] = $ShapeType::Capsule;
boneJointType[1] = $JointType::Hinge;
boneOffset[1] = "0 0 0";
boneJointParam[1] = "0 1.57 0";
//head
boneParentNodeName[2] = "Bip01 Spine2";
boneNodeName[2] = "Bip01 Head";
boneSize[2] = "0.2 0.1 0.0";
boneMass[2] = 1;
boneShape[2] = $ShapeType::Capsule;
boneOffset[2] = "0 0 0";
boneJointType[2] = $JointType::ConeTwist;
boneJointParam[2] = "0.785 -0.785 0.785";
//left arm
//upperarm
boneParentNodeName[3] = "Bip01 Spine2";
boneNodeName[3] = "Bip01 L UpperArm";
boneSize[3] = "0.2 0.3 0.0";
boneMass[3] = 1;//5;
boneShape[3] = $ShapeType::Capsule;
boneOffset[3] = "0 0 0";
boneJointType[3] = $JointType::ConeTwist;
boneJointParam[3] = "0.785 -0.785 0.785";
//forearm
boneParentNodeName[4] = "Bip01 L UpperArm";
boneNodeName[4] = "Bip01 L Forearm";
boneSize[4] = "0.2 0.4 0.0";
boneMass[4] = 1;
boneShape[4] = $ShapeType::Capsule;
boneOffset[4] = "0 0 0";
boneJointType[4] = $JointType::Hinge;
boneJointParam[4] = "-1.57 0 0";
//right arm
//upperarm
boneParentNodeName[5] = "Bip01 Spine2";
boneNodeName[5] = "Bip01 R UpperArm";
boneSize[5] = "0.2 0.3 0.0";
boneMass[5] = 1;
boneShape[5] = $ShapeType::Capsule;
boneOffset[5] = "0 0 0";
boneJointType[5] = $JointType::ConeTwist;
boneJointParam[5] = "0.785 -0.785 0.785";
//forearm
boneParentNodeName[6] = "Bip01 R UpperArm";
boneNodeName[6] = "Bip01 R Forearm";
boneSize[6] = "0.2 0.4 0.0";
boneMass[6] = 1;
boneShape[6] = $ShapeType::Capsule;
boneOffset[6] = "0 0 0";
boneJointType[6] = $JointType::Hinge;
boneJointParam[6] = "-1.57 0 0";
//left leg
//upper
boneParentNodeName[7] = "Bip01 Pelvis";
boneNodeName[7] = "Bip01 L Thigh";
boneSize[7] = "0.2 0.4 0.0";
boneMass[7] = 1;
boneShape[7] = $ShapeType::Capsule;
boneOffset[7] = "0 0 0";
boneJointType[7] = $JointType::ConeTwist;
boneJointParam[7] = "0.785 -0.785 0.785";
//lower
boneParentNodeName[8] = "Bip01 L Thigh";
boneNodeName[8] = "Bip01 L Calf";
boneSize[8] = "0.2 0.4 0.0";
boneMass[8] = 1;
boneShape[8] = $ShapeType::Capsule;
boneOffset[8] = "0 0 0";
boneJointType[8] = $JointType::Hinge;
boneJointParam[8] = "-1.57 0 0";
//right leg
//upper
boneParentNodeName[9] = "Bip01 Pelvis";
boneNodeName[9] = "Bip01 R Thigh";
boneSize[9] = "0.2 0.4 0.0";
boneMass[9] = 1;//7;
boneShape[9] = $ShapeType::Capsule;
boneOffset[9] = "0 0 0";
boneJointType[9] = $JointType::ConeTwist;
boneJointParam[9] = "0.785 -0.785 0.785";
//lower
boneParentNodeName[10] = "Bip01 R Thigh";
boneNodeName[10] = "Bip01 R Calf";
boneSize[10] = "0.2 0.4 0.0";
boneMass[10] = 1;
boneShape[10] = $ShapeType::Capsule;
boneOffset[10] = "0 0 0";
boneJointType[10] = $JointType::Hinge;
boneJointParam[10] = "-1.57 0 0";
};
datablock RagDollData(TorqueOrcRagDoll : SpaceOrcRagDoll)
{
shapeFile = "art/shapes/actors/TorqueOrc/TorqueOrc.dts";
};
datablock RagDollData(ElfRagDoll)
{
category = "RigidBody";
shapeFile = "art/shapes/actors/Elf/Elf.dts";
minContactSpeed = 2.0;
collisionSoundsCount = 1;
collisionSound[0] = bodyFall0;
//pelvis
boneNodeName[0] = "Bip01 Pelvis";
boneSize[0] = "0.2 0.2 0.7";
boneMass[0] = 2;
boneShape[0] = $ShapeType::Capsule;
boneOffset[0] = "0 0 0";
//torso
boneParentNodeName[1] = "Bip01 Pelvis";
boneNodeName[1] = "Bip01 Spine2";
boneSize[1] = "0.2 0.2 0.7";
boneMass[1] = 2;
boneShape[1] = $ShapeType::Capsule;
boneOffset[1] = "-0.3 0 0";
boneJointType[1] = $JointType::Hinge;
boneJointParam[1] = "0 1.57 0";
//head
boneParentNodeName[2] = "Bip01 Spine2";
boneNodeName[2] = "Bip01 Head";
boneSize[2] = "0.2 0.2 0.2";
boneMass[2] = 1;
boneShape[2] = $ShapeType::Capsule;
boneOffset[2] = "0 0 0";
boneJointType[2] = $JointType::ConeTwist;
boneJointParam[2] = "0.785 -0.785 0.785";
//left arm
//upperarm
boneParentNodeName[3] = "Bip01 Spine2";
boneNodeName[3] = "Bip01 L UpperArm";
boneSize[3] = "0.1 0.2 0.2";
boneMass[3] = 1;
boneShape[3] = $ShapeType::Capsule;
boneOffset[3] = "0.1 0 0";
boneJointType[3] = $JointType::ConeTwist;
boneJointParam[3] = "0.785 -0.785 0.785";
//forearm
boneParentNodeName[4] = "Bip01 L UpperArm";
boneNodeName[4] = "Bip01 L Forearm";
boneSize[4] = "0.1 0.2 0.2";
boneMass[4] = 1;
boneShape[4] = $ShapeType::Capsule;
boneOffset[4] = "0.1 0 0";
boneJointType[4] = $JointType::Hinge;
boneJointParam[4] = "-1.57 0 0";
//right arm
//upperarm
boneParentNodeName[5] = "Bip01 Spine2";
boneNodeName[5] = "Bip01 R UpperArm";
boneSize[5] = "0.1 0.2 0.2";
boneMass[5] = 1;
boneShape[5] = $ShapeType::Capsule;
boneOffset[5] = "0.1 0 0";
boneJointType[5] = $JointType::ConeTwist;
boneJointParam[5] = "0.785 -0.785 0.785";
//forearm
boneParentNodeName[6] = "Bip01 R UpperArm";
boneNodeName[6] = "Bip01 R Forearm";
boneSize[6] = "0.1 0.2 0.2";
boneMass[6] =1;
boneShape[6] = $ShapeType::Capsule;
boneOffset[6] = "0.1 0 0";
boneJointType[6] = $JointType::Hinge;
boneJointParam[6] = "-1.57 0 0";
//left leg
//upper
boneParentNodeName[7] = "Bip01 Pelvis";
boneNodeName[7] = "Bip01 L Thigh";
boneSize[7] = "0.15 0.4 0.2";
boneMass[7] = 1;
boneShape[7] = $ShapeType::Capsule;
boneOffset[7] = "0.0 0 0";
boneJointType[7] = $JointType::ConeTwist;
boneJointParam[7] = "0.785 -0.785 0.785";
//lower
boneParentNodeName[8] = "Bip01 L Thigh";
boneNodeName[8] = "Bip01 L Calf";
boneSize[8] = "0.15 0.4 0.2";
boneMass[8] = 1;
boneShape[8] = $ShapeType::Capsule;
boneOffset[8] = "0.0 0 0";
boneJointType[8] = $JointType::Hinge;
boneJointParam[8] = "-1.57 0 0 ";
//right leg
//upper
boneParentNodeName[9] = "Bip01 Pelvis";
boneNodeName[9] = "Bip01 R Thigh";
boneSize[9] = "0.15 0.4 0.2";
boneMass[9] = 1;
boneShape[9] = $ShapeType::Capsule;
boneOffset[9] = "0.0 0 0";
boneJointType[9] = $JointType::ConeTwist;
boneJointParam[9] = "0.785 -0.785 0.785";
//lower
boneParentNodeName[10] = "Bip01 R Thigh";
boneNodeName[10] = "Bip01 R Calf";
boneSize[10] = "0.15 0.4 0.2";
boneMass[10] = 1;
boneShape[10] = $ShapeType::Capsule;
boneOffset[10] = "0.0 0 0";
boneJointType[10] = $JointType::Hinge;
boneJointParam[10] = "-1.57 0 0";
};
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbTreeConnectAndx Request
/// </summary>
public class SmbTreeConnectAndxRequestPacket : SmbBatchedRequestPacket
{
#region Fields
private SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters smbParameters;
private SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Data smbData;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters
/// </summary>
public SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Data
/// </summary>
public SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
/// <summary>
/// the SmbCommand of the andx packet.
/// </summary>
protected override SmbCommand AndxCommand
{
get
{
return this.SmbParameters.AndXCommand;
}
}
/// <summary>
/// Set the AndXOffset from batched request
/// </summary>
protected override ushort AndXOffset
{
get
{
return this.smbParameters.AndXOffset;
}
set
{
this.smbParameters.AndXOffset = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbTreeConnectAndxRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbTreeConnectAndxRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbTreeConnectAndxRequestPacket(SmbTreeConnectAndxRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.AndXCommand = packet.SmbParameters.AndXCommand;
this.smbParameters.AndXReserved = packet.SmbParameters.AndXReserved;
this.smbParameters.AndXOffset = packet.SmbParameters.AndXOffset;
this.smbParameters.Flags = packet.SmbParameters.Flags;
this.smbParameters.PasswordLength = packet.SmbParameters.PasswordLength;
this.smbData.ByteCount = packet.SmbData.ByteCount;
if (packet.smbData.Password != null)
{
this.smbData.Password = new byte[packet.smbData.Password.Length];
Array.Copy(packet.smbData.Password, this.smbData.Password, packet.smbParameters.PasswordLength);
}
else
{
this.smbData.Password = new byte[0];
}
if (packet.smbData.Pad != null)
{
this.smbData.Pad = new byte[packet.smbData.Pad.Length];
Array.Copy(packet.smbData.Pad, this.smbData.Pad, packet.smbData.Pad.Length);
}
else
{
this.smbData.Pad = new byte[0];
}
if (packet.smbData.Path != null)
{
this.smbData.Path = new byte[packet.smbData.Path.Length];
Array.Copy(packet.smbData.Path, this.smbData.Path, packet.smbData.Path.Length);
}
else
{
this.smbData.Path = new byte[0];
}
if (packet.smbData.Service != null)
{
this.smbData.Service = new byte[packet.smbData.Service.Length];
Array.Copy(packet.smbData.Service, this.smbData.Service, packet.smbData.Service.Length);
}
else
{
this.smbData.Service = new byte[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbTreeConnectAndxRequestPacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = CifsMessageUtils.ToStuct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
this.smbDataBlock.ByteCount = this.SmbData.ByteCount;
this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
if (this.SmbData.Password != null)
{
channel.WriteBytes(this.SmbData.Password);
}
if (this.SmbData.Pad != null)
{
channel.WriteBytes(this.SmbData.Pad);
}
if (this.SmbData.Path != null)
{
channel.WriteBytes(this.SmbData.Path);
}
if (this.SmbData.Service != null)
{
channel.WriteBytes(this.SmbData.Service);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_TREE_CONNECT_ANDX_Request_SMB_Parameters>(
TypeMarshal.ToBytes(this.smbParametersBlock));
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.ByteCount = channel.Read<ushort>();
this.smbData.Password = channel.ReadBytes(this.SmbParameters.PasswordLength);
// pad:
if ((Marshal.SizeOf(this.SmbHeader) + Marshal.SizeOf(this.SmbParameters)
+ Marshal.SizeOf(this.smbData.ByteCount) + this.SmbParameters.PasswordLength) % 2 != 0)
{
this.smbData.Pad = channel.ReadBytes(1);
}
else
{
this.smbData.Pad = new byte[0];
}
// Path:
this.smbData.Path = CifsMessageUtils.ReadNullTerminatedString(channel,
(this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE);
// Service:
this.smbData.Service = channel.ReadBytes(this.smbData.ByteCount - this.smbData.Password.Length
- this.smbData.Pad.Length - this.smbData.Path.Length);
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.Pad = new byte[0];
this.smbData.Password = new byte[0];
this.smbData.Path = new byte[0];
this.smbData.Service = new byte[0];
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Impl;
namespace EasyNetQ.Tests
{
public sealed class BasicProperties : IBasicProperties
{
private string _contentType;
private string _contentEncoding;
private IDictionary<string, object> _headers;
private byte _deliveryMode;
private byte _priority;
private string _correlationId;
private string _replyTo;
private string _expiration;
private string _messageId;
private AmqpTimestamp _timestamp;
private string _type;
private string _userId;
private string _appId;
private string _clusterId;
private bool _contentType_present = false;
private bool _contentEncoding_present = false;
private bool _headers_present = false;
private bool _deliveryMode_present = false;
private bool _priority_present = false;
private bool _correlationId_present = false;
private bool _replyTo_present = false;
private bool _expiration_present = false;
private bool _messageId_present = false;
private bool _timestamp_present = false;
private bool _type_present = false;
private bool _userId_present = false;
private bool _appId_present = false;
private bool _clusterId_present = false;
public string ContentType
{
get => _contentType;
set
{
_contentType_present = value != null;
_contentType = value;
}
}
public string ContentEncoding
{
get => _contentEncoding;
set
{
_contentEncoding_present = value != null;
_contentEncoding = value;
}
}
public IDictionary<string, object> Headers
{
get => _headers;
set
{
_headers_present = value != null;
_headers = value;
}
}
public byte DeliveryMode
{
get => _deliveryMode;
set
{
_deliveryMode_present = true;
_deliveryMode = value;
}
}
public bool Persistent
{
get { return DeliveryMode == 2; }
set { DeliveryMode = value ? (byte)2 : (byte)1; }
}
public byte Priority
{
get => _priority;
set
{
_priority_present = true;
_priority = value;
}
}
public string CorrelationId
{
get => _correlationId;
set
{
_correlationId_present = value != null;
_correlationId = value;
}
}
public string ReplyTo
{
get => _replyTo;
set
{
_replyTo_present = value != null;
_replyTo = value;
}
}
public string Expiration
{
get => _expiration;
set
{
_expiration_present = value != null;
_expiration = value;
}
}
public string MessageId
{
get => _messageId;
set
{
_messageId_present = value != null;
_messageId = value;
}
}
public AmqpTimestamp Timestamp
{
get => _timestamp;
set
{
_timestamp_present = true;
_timestamp = value;
}
}
public string Type
{
get => _type;
set
{
_type_present = value != null;
_type = value;
}
}
public string UserId
{
get => _userId;
set
{
_userId_present = value != null;
_userId = value;
}
}
public string AppId
{
get => _appId;
set
{
_appId_present = value != null;
_appId = value;
}
}
public string ClusterId
{
get => _clusterId;
set
{
_clusterId_present = value != null;
_clusterId = value;
}
}
public void ClearContentType() => _contentType_present = false;
public void ClearContentEncoding() => _contentEncoding_present = false;
public void ClearHeaders() => _headers_present = false;
public void ClearDeliveryMode() => _deliveryMode_present = false;
public void ClearPriority() => _priority_present = false;
public void ClearCorrelationId() => _correlationId_present = false;
public void ClearReplyTo() => _replyTo_present = false;
public void ClearExpiration() => _expiration_present = false;
public void ClearMessageId() => _messageId_present = false;
public void ClearTimestamp() => _timestamp_present = false;
public void ClearType() => _type_present = false;
public void ClearUserId() => _userId_present = false;
public void ClearAppId() => _appId_present = false;
public void ClearClusterId() => _clusterId_present = false;
public bool IsContentTypePresent() => _contentType_present;
public bool IsContentEncodingPresent() => _contentEncoding_present;
public bool IsHeadersPresent() => _headers_present;
public bool IsDeliveryModePresent() => _deliveryMode_present;
public bool IsPriorityPresent() => _priority_present;
public bool IsCorrelationIdPresent() => _correlationId_present;
public bool IsReplyToPresent() => _replyTo_present;
public bool IsExpirationPresent() => _expiration_present;
public bool IsMessageIdPresent() => _messageId_present;
public bool IsTimestampPresent() => _timestamp_present;
public bool IsTypePresent() => _type_present;
public bool IsUserIdPresent() => _userId_present;
public bool IsAppIdPresent() => _appId_present;
public bool IsClusterIdPresent() => _clusterId_present;
public PublicationAddress ReplyToAddress
{
get { return PublicationAddress.Parse(ReplyTo); }
set { ReplyTo = value.ToString(); }
}
public BasicProperties() { }
public ushort ProtocolClassId => 60;
public string ProtocolClassName => "basic";
public void AppendPropertyDebugStringTo(StringBuilder sb)
{
sb.Append("(");
sb.Append("content-type="); sb.Append(_contentType_present ? (_contentType == null ? "(null)" : _contentType.ToString()) : "_"); sb.Append(", ");
sb.Append("content-encoding="); sb.Append(_contentEncoding_present ? (_contentEncoding == null ? "(null)" : _contentEncoding.ToString()) : "_"); sb.Append(", ");
sb.Append("headers="); sb.Append(_headers_present ? (_headers == null ? "(null)" : _headers.ToString()) : "_"); sb.Append(", ");
sb.Append("delivery-mode="); sb.Append(_deliveryMode_present ? _deliveryMode.ToString() : "_"); sb.Append(", ");
sb.Append("priority="); sb.Append(_priority_present ? _priority.ToString() : "_"); sb.Append(", ");
sb.Append("correlation-id="); sb.Append(_correlationId_present ? (_correlationId == null ? "(null)" : _correlationId.ToString()) : "_"); sb.Append(", ");
sb.Append("reply-to="); sb.Append(_replyTo_present ? (_replyTo == null ? "(null)" : _replyTo.ToString()) : "_"); sb.Append(", ");
sb.Append("expiration="); sb.Append(_expiration_present ? (_expiration == null ? "(null)" : _expiration.ToString()) : "_"); sb.Append(", ");
sb.Append("message-id="); sb.Append(_messageId_present ? (_messageId == null ? "(null)" : _messageId.ToString()) : "_"); sb.Append(", ");
sb.Append("timestamp="); sb.Append(_timestamp_present ? _timestamp.ToString() : "_"); sb.Append(", ");
sb.Append("type="); sb.Append(_type_present ? (_type == null ? "(null)" : _type.ToString()) : "_"); sb.Append(", ");
sb.Append("user-id="); sb.Append(_userId_present ? (_userId == null ? "(null)" : _userId.ToString()) : "_"); sb.Append(", ");
sb.Append("app-id="); sb.Append(_appId_present ? (_appId == null ? "(null)" : _appId.ToString()) : "_"); sb.Append(", ");
sb.Append("cluster-id="); sb.Append(_clusterId_present ? (_clusterId == null ? "(null)" : _clusterId.ToString()) : "_");
sb.Append(")");
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.ViewServices;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.GestionContenu.Contenu.Tabs.Search;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Contenu;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionContenu.Contenu;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.DataGrid.Manager;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionContenu.Contenu.Tabs
{
public class SearchViewModel : TabBase, IDisposable
{
private readonly IResourceWrapper _resourceWrapper;
private readonly ILoaderReferentiel _referentiel;
private readonly INotificationViewService _notificationService;
private readonly IDepotConfigurationPage _configurationPageDepot;
private readonly IModelBuilderDetails _builderDetails;
private ObservableCollection<ConfigurationPageResult> _searchResult;
private bool _searchOverflow;
private bool _isLoading;
private ICommand _resetCommand;
private ICommand _searchCommand;
private ICommand _doubleClickCommand;
private DataGridColumnManager _manager;
private SearchEntityViewModel _entity;
protected ChannelObserver<UpdateListMessage> ObserverUpdateList { get; private set; }
[ResolveConstructor]
public SearchViewModel(IResourceWrapper resourceWrapper, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, INotificationViewService notificationService, IDepotConfigurationPage configurationPageDepot, IModelBuilderDetails builderDetails)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_referentiel = referentiel;
_notificationService = notificationService;
_configurationPageDepot = configurationPageDepot;
_builderDetails = builderDetails;
InitializeCommands();
InitializeMessenging();
InitializeUI();
}
public DataGridColumnManager DataGridManager
{
get
{
return _manager;
}
set
{
if (_manager != value)
{
_manager = value;
NotifyPropertyChanged(() => DataGridManager);
}
}
}
public ObservableCollection<ConfigurationPageResult> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public bool SearchOverflow
{
get
{
return _searchOverflow;
}
set
{
if (_searchOverflow != value)
{
_searchOverflow = value;
NotifyPropertyChanged(() => SearchOverflow);
}
}
}
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
public ICommand ResetCommand
{
get
{
return _resetCommand;
}
set
{
if (_resetCommand != value)
{
_resetCommand = value;
NotifyPropertyChanged(() => ResetCommand);
}
}
}
/// <summary>
/// Command de recherche des personnes.
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
public SearchEntityViewModel Entity
{
get
{
return _entity;
}
set
{
if (_entity != value)
{
_entity = value;
NotifyPropertyChanged(() => Entity);
}
}
}
private void InitializeCommands()
{
_resetCommand = new ActionCommand(OnReset);
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<ConfigurationPageResult>(OnDoubleClickCommand);
}
private void InitializeMessenging()
{
ObserverUpdateList = _messengingService.CreateObserver<UpdateListMessage>(Msg =>
{
if (Msg.Type != TypeUpdateList.RechercheReferentiels)
return;
});
ObserverUpdateList.Subscribe(ThreadOption.UIThread);
}
private void InitializeUI()
{
SearchResult = new ObservableCollection<ConfigurationPageResult>();
SearchOverflow = false;
IsLoading = false;
Entity = new SearchEntityViewModel(_referentiel);
DataGridManager = new DataGridColumnManager();
}
private void DisposeMessenging()
{
ObserverUpdateList.Unsubscribe();
}
private void OnReset()
{
Entity.Criterias.Reset();
}
private void OnSearch()
{
if (IsLoading)
return;
Entity.Criterias.NotifyAllCheckError(Entity.Criterias);
if (Entity.Criterias.HasErrors)
{
var message = _resourceWrapper.ErrorsResourceManager.GetString("ERROR_CHECK");
_notificationService.ShowNotification(message);
return;
}
var limitValue = _referentiel.Referentiel.Parametres.Where(x => x.Code.Equals("SearchContenuLimit")).Select(x => x.Valeur).FirstOrDefault();
var limit = Convert.ToInt32(limitValue);
var criterias = AutoMapper.Mapper.Map<SearchContenuEntityCriteriasViewModel, SearchContenuCriteriasDto>(Entity.Criterias);
_configurationPageDepot.Search(
criterias,
r =>
{
foreach (var P in r)
SearchResult.Add(P);
SearchOverflow = SearchResult.Count == limit;
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(ConfigurationPageResult selected)
{
if (selected != null)
{
ContenuHelper.AddContenuTab(selected.ID, _messengingService, _applicationContext, _configurationPageDepot, _builderDetails);
}
}
public void Dispose()
{
DisposeMessenging();
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper ([email protected])
//
// 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using Libev;
using Manos.IO;
using Manos.Collections;
namespace Manos.Http {
public class HttpResponse : HttpEntity, IHttpResponse {
private StreamWriter writer;
private Dictionary<string, HttpCookie> cookies;
public HttpResponse (Context context, IHttpRequest request, ITcpSocket socket)
: base (context)
{
Request = request;
Socket = socket;
StatusCode = 200;
WriteHeaders = true;
Stream = new HttpStream (this, socket.GetSocketStream ());
Stream.Chunked = (request.MajorVersion > 0 && request.MinorVersion > 0);
}
public IHttpRequest Request {
get;
private set;
}
public StreamWriter Writer {
get {
if (writer == null)
writer = new StreamWriter (new HttpStreamWriterWrapper (Stream));
return writer;
}
}
public int StatusCode {
get;
set;
}
public bool WriteHeaders {
get;
set;
}
public Dictionary<string,HttpCookie> Cookies {
get {
if (cookies == null)
cookies = new Dictionary<string, HttpCookie> ();
return cookies;
}
}
public void Redirect (string url)
{
StatusCode = 302;
Headers.SetNormalizedHeader ("Location", url);
// WriteMetadata ();
End ();
}
public override void WriteMetadata (StringBuilder builder)
{
WriteStatusLine (builder);
if (WriteHeaders) {
Headers.Write (builder, cookies == null ? null : Cookies.Values, Encoding.ASCII);
}
}
public void SetHeader (string name, string value)
{
Headers.SetHeader (name, value);
}
public void SetCookie (string name, HttpCookie cookie)
{
Cookies [name] = cookie;
}
public HttpCookie SetCookie (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
if (value == null)
throw new ArgumentNullException ("value");
var cookie = new HttpCookie (name, value);
SetCookie (name, cookie);
return cookie;
}
public HttpCookie SetCookie (string name, string value, string domain)
{
if (name == null)
throw new ArgumentNullException ("name");
if (value == null)
throw new ArgumentNullException ("value");
var cookie = new HttpCookie (name, value);
cookie.Domain = domain;
SetCookie (name, cookie);
return cookie;
}
public HttpCookie SetCookie (string name, string value, DateTime expires)
{
return SetCookie (name, value, null, expires);
}
public HttpCookie SetCookie (string name, string value, string domain, DateTime expires)
{
if (name == null)
throw new ArgumentNullException ("name");
if (value == null)
throw new ArgumentNullException ("value");
var cookie = new HttpCookie (name, value);
cookie.Domain = domain;
cookie.Expires = expires;
SetCookie (name, cookie);
return cookie;
}
public HttpCookie SetCookie (string name, string value, TimeSpan max_age)
{
return SetCookie (name, value, DateTime.Now + max_age);
}
public HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age)
{
return SetCookie (name, value, domain, DateTime.Now + max_age);
}
public void RemoveCookie(string name)
{
var cookie = new HttpCookie (name, "");
cookie.Expires = DateTime.Now.AddYears(-1);
SetCookie (name, cookie);
}
public override void Reset ()
{
cookies = null;
base.Reset ();
}
public override ParserSettings CreateParserSettings ()
{
ParserSettings settings = new ParserSettings ();
settings.OnBody = OnBody;
return settings;
}
protected override int OnHeadersComplete (HttpParser parser)
{
base.OnHeadersComplete (parser);
StatusCode = parser.StatusCode;
if (Request.Method == HttpMethod.HTTP_HEAD)
return 1;
return 0;
}
private void WriteStatusLine (StringBuilder builder)
{
builder.Append ("HTTP/");
builder.Append (Request.MajorVersion);
builder.Append (".");
builder.Append (Request.MinorVersion);
builder.Append (" ");
builder.Append (StatusCode);
builder.Append (" ");
builder.Append (GetStatusDescription (StatusCode));
builder.Append ("\r\n");
}
private static string GetStatusDescription (int code)
{
switch (code){
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request-Uri Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 422: return "Unprocessable Entity";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "Http Version Not Supported";
case 507: return "Insufficient Storage";
}
return "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public class PropertyResolver
{
public string[] ExcludedFieldNames { get; set; }
public Type[] ExcludedTypes { get; set; }
public Type[] AllowedTypes { get; set; }
public PropertyResolver ()
{
ExcludedFieldNames = new string[] {};
ExcludedTypes = new Type[] {};
AllowedTypes = new Type[] {};
}
public IList<string> GetFieldsAndPropertiesUnderPath(GameObject go, string propertPath)
{
propertPath = propertPath.Trim ();
if (!PropertyPathIsValid (propertPath))
{
throw new ArgumentException("Incorrent property path: " + propertPath);
}
var idx = propertPath.LastIndexOf('.');
if (idx < 0)
{
var components = GetFieldsAndPropertiesFromGameObject(go, 2, null);
return components;
}
var propertyToSearch = propertPath;
Type type = null;
try
{
type = GetPropertyTypeFromString(go, propertyToSearch);
idx = propertPath.Length-1;
}
catch(ArgumentException)
{
try
{
propertyToSearch = propertPath.Substring(0, idx);
type = GetPropertyTypeFromString(go, propertyToSearch);
}
catch (NullReferenceException)
{
var components = GetFieldsAndPropertiesFromGameObject(go, 2, null);
return components.Where(s => s.StartsWith(propertPath.Substring(idx + 1))).ToArray();
}
}
var resultList = new List<string>();
var path = "";
if(propertyToSearch.EndsWith("."))
propertyToSearch = propertyToSearch.Substring(0, propertyToSearch.Length-1);
foreach(var c in propertyToSearch)
{
if(c == '.')
resultList.Add(path);
path += c;
}
resultList.Add(path);
foreach (var prop in type.GetProperties())
{
if (prop.Name.StartsWith(propertPath.Substring(idx + 1)))
resultList.Add(propertyToSearch + "." + prop.Name);
}
foreach (var prop in type.GetFields())
{
if (prop.Name.StartsWith(propertPath.Substring(idx + 1)))
resultList.Add(propertyToSearch + "." + prop.Name);
}
return resultList.ToArray();
}
internal bool PropertyPathIsValid ( string propertPath )
{
if (propertPath.StartsWith ("."))
return false;
if (propertPath.IndexOf ("..") >= 0)
return false;
if (Regex.IsMatch (propertPath,
@"\s"))
return false;
return true;
}
public IList<string> GetFieldsAndPropertiesFromGameObject ( GameObject gameObject, int depthOfSearch, string extendPath )
{
if(depthOfSearch<1) throw new ArgumentOutOfRangeException("depthOfSearch need to be greater than 0");
var goVals = GetPropertiesAndFieldsFromType(typeof(GameObject),
depthOfSearch - 1).Select(s => "gameObject." + s);
var result = new List<string>();
if (AllowedTypes == null || !AllowedTypes.Any() || AllowedTypes.Contains(typeof(GameObject)))
result.Add("gameObject");
result.AddRange (goVals);
foreach (var componentType in GetAllComponents(gameObject))
{
if (AllowedTypes == null || !AllowedTypes.Any() || AllowedTypes.Contains(componentType))
result.Add(componentType.Name);
if (depthOfSearch > 1)
{
var vals = GetPropertiesAndFieldsFromType (componentType,
depthOfSearch - 1 );
var valsFullName = vals.Select (s => componentType.Name + "." + s);
result.AddRange (valsFullName);
}
}
if (!string.IsNullOrEmpty (extendPath))
{
var pathType = GetPropertyTypeFromString (gameObject,
extendPath);
var vals = GetPropertiesAndFieldsFromType (pathType,
depthOfSearch - 1);
var valsFullName = vals.Select (s => extendPath + "." + s);
result.AddRange (valsFullName);
}
return result;
}
private string[] GetPropertiesAndFieldsFromType ( Type type, int level )
{
level--;
var result = new List<string>();
var fields = new List<MemberInfo>();
fields.AddRange(type.GetFields());
fields.AddRange(type.GetProperties());
foreach (var member in fields)
{
var memberType = GetMemberFieldType(member);
var memberTypeName = memberType.Name;
if (AllowedTypes == null
||!AllowedTypes.Any()
|| (AllowedTypes.Contains(memberType) && !ExcludedFieldNames.Contains(memberTypeName))
)
{
result.Add(member.Name);
}
if (level > 0 && IsTypeOrNameNotExcluded(memberType, memberTypeName))
{
var vals = GetPropertiesAndFieldsFromType(memberType,
level);
var valsFullName = vals.Select(s => member.Name + "." + s);
result.AddRange(valsFullName);
}
}
return result.ToArray();
}
private Type GetMemberFieldType ( MemberInfo info )
{
if (info.MemberType == MemberTypes.Property)
return (info as PropertyInfo).PropertyType;
if (info.MemberType == MemberTypes.Field)
return (info as FieldInfo).FieldType;
throw new Exception("Only properties and fields are allowed");
}
internal Type[] GetAllComponents ( GameObject gameObject )
{
var result = new List<Type>();
var components = gameObject.GetComponents(typeof(Component));
foreach (var component in components)
{
var componentType = component.GetType();
if (IsTypeOrNameNotExcluded(componentType, null))
{
result.Add(componentType);
}
}
return result.ToArray();
}
private bool IsTypeOrNameNotExcluded(Type memberType, string memberTypeName)
{
return !ExcludedTypes.Contains(memberType)
&& !ExcludedFieldNames.Contains(memberTypeName);
}
#region Static helpers
public static object GetPropertyValueFromString(GameObject gameObj, string propertyPath)
{
if (propertyPath == "")
return gameObj;
var propsQueue = new Queue<string>(propertyPath.Split('.').Where(s => !string.IsNullOrEmpty(s)));
if (propsQueue == null) throw new ArgumentException("Incorrent property path");
object result;
if (char.IsLower(propsQueue.Peek()[0]))
{
result = gameObj;
}
else
{
result = gameObj.GetComponent(propsQueue.Dequeue());
}
Type type = result.GetType();
while (propsQueue.Count != 0)
{
var nameToFind = propsQueue.Dequeue();
var property = type.GetProperty(nameToFind);
if (property != null)
{
result = property.GetGetMethod().Invoke(result,
null);
}
else
{
var field = type.GetField(nameToFind);
result = field.GetValue(result);
}
type = result.GetType();
}
return result;
}
private static Type GetPropertyTypeFromString(GameObject gameObj, string propertyPath)
{
if (propertyPath == "")
return gameObj.GetType();
var propsQueue = new Queue<string>(propertyPath.Split('.').Where(s => !string.IsNullOrEmpty(s)));
if (propsQueue == null) throw new ArgumentException("Incorrent property path");
Type result;
if (char.IsLower(propsQueue.Peek()[0]))
{
result = gameObj.GetType();
}
else
{
var component = gameObj.GetComponent(propsQueue.Dequeue());
if (component == null) throw new ArgumentException("Incorrent property path");
result = component.GetType();
}
while (propsQueue.Count != 0)
{
var nameToFind = propsQueue.Dequeue();
var property = result.GetProperty(nameToFind);
if (property != null)
{
result = property.PropertyType;
}
else
{
var field = result.GetField(nameToFind);
if (field == null) throw new ArgumentException("Incorrent property path");
result = field.FieldType;
}
}
return result;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace JetBrains.Annotations
{
/// <summary>
/// Indicates that marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor.
/// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
private readonly string myFormatParameterName;
/// <summary>
/// Initializes new instance of StringFormatMethodAttribute
/// </summary>
/// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param>
public StringFormatMethodAttribute(string formatParameterName)
{
myFormatParameterName = formatParameterName;
}
/// <summary>
/// Gets format parameter name
/// </summary>
public string FormatParameterName
{
get { return myFormatParameterName; }
}
}
/// <summary>
/// Indicates that the function argument should be string literal and match one of the parameters of the caller function.
/// For example, <see cref="ArgumentNullException"/> has such parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute
{
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied.
/// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute
/// </summary>
/// <seealso cref="AssertionConditionAttribute"/>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AssertionMethodAttribute : Attribute
{
}
/// <summary>
/// Indicates the condition parameter of the assertion method.
/// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute.
/// The mandatory argument of the attribute is the assertion type.
/// </summary>
/// <seealso cref="AssertionConditionType"/>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class AssertionConditionAttribute : Attribute
{
private readonly AssertionConditionType myConditionType;
/// <summary>
/// Initializes new instance of AssertionConditionAttribute
/// </summary>
/// <param name="conditionType">Specifies condition type</param>
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
myConditionType = conditionType;
}
/// <summary>
/// Gets condition type
/// </summary>
public AssertionConditionType ConditionType
{
get { return myConditionType; }
}
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues.
/// Otherwise, execution is assumed to be halted
/// </summary>
public enum AssertionConditionType
{
/// <summary>
/// Indicates that the marked parameter should be evaluated to true
/// </summary>
IS_TRUE = 0,
/// <summary>
/// Indicates that the marked parameter should be evaluated to false
/// </summary>
IS_FALSE = 1,
/// <summary>
/// Indicates that the marked parameter should be evaluated to null value
/// </summary>
IS_NULL = 2,
/// <summary>
/// Indicates that the marked parameter should be evaluated to not null vaalue
/// </summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class TerminatesProgramAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could never be <c>null</c>
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators.
/// There is only exception to compare with <c>null</c>, it is permitted
/// </summary>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute
{
}
/// <summary>
/// When applied to target attribute, specifies a requirement for any type which is marked with
/// target attribute to implement or inherit specific type or types
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute
/// {}
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent
/// {}
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
private readonly Type[] myBaseTypes;
/// <summary>
/// Initializes new instance of BaseTypeRequiredAttribute
/// </summary>
/// <param name="baseTypes">Specifies which types are required</param>
public BaseTypeRequiredAttribute(params Type[] baseTypes)
{
myBaseTypes = baseTypes;
}
/// <summary>
/// Gets enumerations of specified base types
/// </summary>
public IEnumerable<Type> BaseTypes
{
get { return myBaseTypes; }
}
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class UsedImplicitlyAttribute : Attribute
{
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseFlags Flags { get; private set; }
/// <summary>
/// Initializes new instance of UsedImplicitlyAttribute
/// </summary>
public UsedImplicitlyAttribute()
: this(ImplicitUseFlags.Default)
{
}
/// <summary>
/// Initializes new instance of UsedImplicitlyAttribute with specified flags
/// </summary>
/// <param name="flags">Value of type <see cref="ImplicitUseFlags"/> indicating usage kind</param>
public UsedImplicitlyAttribute(ImplicitUseFlags flags)
{
Flags = flags;
}
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MeansImplicitUseAttribute : Attribute
{
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseFlags Flags { get; private set; }
/// <summary>
/// Initializes new instance of MeansImplicitUseAttribute
/// </summary>
[UsedImplicitly]
public MeansImplicitUseAttribute()
: this(ImplicitUseFlags.Default)
{
}
/// <summary>
/// Initializes new instance of MeansImplicitUseAttribute with specified flags
/// </summary>
/// <param name="flags">Value of type <see cref="ImplicitUseFlags"/> indicating usage kind</param>
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseFlags flags)
{
Flags = flags;
}
}
/// <summary>
/// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseFlags
{
/// <summary>
/// Only entity marked with attribute considered used
/// </summary>
Default = 0,
/// <summary>
/// Entity marked with attribute and all its members considered used
/// </summary>
IncludeMembers = 1
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Collections.Generic;
using System;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Cmdlet to get available list of results
/// </summary>
[Cmdlet(VerbsCommon.Get, "Job", DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113328")]
[OutputType(typeof(Job))]
public class GetJobCommand : JobCmdletBase
{
#region Parameters
/// <summary>
/// IncludeChildJob parameter.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public SwitchParameter IncludeChildJob { get; set; }
/// <summary>
/// ChildJobState parameter.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public JobState ChildJobState { get; set; }
/// <summary>
/// HasMoreData parameter.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public bool HasMoreData { get; set; }
/// <summary>
/// Before time filter.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public DateTime Before { get; set; }
/// <summary>
/// After time filter.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public DateTime After { get; set; }
/// <summary>
/// Newest returned count.
/// </summary>
[Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)]
[Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)]
public int Newest { get; set; }
/// <summary>
/// SessionId for which job
/// need to be obtained
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, Position = 0,
ParameterSetName = JobCmdletBase.SessionIdParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public override int[] Id
{
get
{
return base.Id;
}
set
{
base.Id = value;
}
}
#endregion Parameters
#region Overrides
/// <summary>
/// Extract resutl objects corresponding to the specified
/// names or expressions
/// </summary>
protected override void ProcessRecord()
{
List<Job> jobList = FindJobs();
jobList.Sort((x, y) => x != null ? x.Id.CompareTo(y != null ? y.Id : 1) : -1);
WriteObject(jobList, true);
} // ProcessRecord
#endregion Overrides
#region Protected Members
/// <summary>
/// Helper method to find jobs based on parameter set.
/// </summary>
/// <returns>Matching jobs</returns>
protected List<Job> FindJobs()
{
List<Job> jobList = new List<Job>();
switch (ParameterSetName)
{
case NameParameterSet:
{
jobList.AddRange(FindJobsMatchingByName(true, false, true, false));
}
break;
case InstanceIdParameterSet:
{
jobList.AddRange(FindJobsMatchingByInstanceId(true, false, true, false));
}
break;
case SessionIdParameterSet:
{
if (Id != null)
{
jobList.AddRange(FindJobsMatchingBySessionId(true, false, true, false));
}
else
{
// Get-Job with no filter.
jobList.AddRange(JobRepository.Jobs);
jobList.AddRange(JobManager.GetJobs(this, true, false, null));
}
}
break;
case CommandParameterSet:
{
jobList.AddRange(FindJobsMatchingByCommand(false));
}
break;
case StateParameterSet:
{
jobList.AddRange(FindJobsMatchingByState(false));
}
break;
case FilterParameterSet:
{
jobList.AddRange(FindJobsMatchingByFilter(false));
}
break;
default:
break;
}
jobList.AddRange(FindChildJobs(jobList));
jobList = ApplyHasMoreDataFiltering(jobList);
return ApplyTimeFiltering(jobList);
}
#endregion
#region Private Members
/// <summary>
/// Filter jobs based on HasMoreData
/// </summary>
///
/// <param name="jobList"></param>
/// <returns>return the list of jobs after applying HasMoreData filter</returns>
private List<Job> ApplyHasMoreDataFiltering(List<Job> jobList)
{
bool hasMoreDataParameter = MyInvocation.BoundParameters.ContainsKey("HasMoreData");
if (!hasMoreDataParameter)
{
return jobList;
}
List<Job> matches = new List<Job>();
foreach (Job job in jobList)
{
if (job.HasMoreData == HasMoreData)
{
matches.Add(job);
}
}
return matches;
}
/// <summary>
/// Find the all child jobs with specified ChildJobState in the job list
/// </summary>
///
/// <param name="jobList"></param>
/// <returns>returns job list including all child jobs with ChildJobState or all if IncludeChildJob is specified</returns>
private List<Job> FindChildJobs(List<Job> jobList)
{
bool childJobStateParameter = MyInvocation.BoundParameters.ContainsKey("ChildJobState");
bool includeChildJobParameter = MyInvocation.BoundParameters.ContainsKey("IncludeChildJob");
List<Job> matches = new List<Job>();
if (!childJobStateParameter && !includeChildJobParameter)
{
return matches;
}
// add all child jobs if ChildJobState is not specified
//
if (!childJobStateParameter && includeChildJobParameter)
{
foreach (Job job in jobList)
{
if (job.ChildJobs != null && job.ChildJobs.Count > 0)
{
matches.AddRange(job.ChildJobs);
}
}
}
else
{
foreach (Job job in jobList)
{
foreach (Job childJob in job.ChildJobs)
{
if (childJob.JobStateInfo.State != ChildJobState) continue;
matches.Add(childJob);
}
}
}
return matches;
}
/// <summary>
/// Applys the appropriate time filter to each job in the job list.
/// Only Job2 type jobs can be time filtered so older Job types are skipped.
/// </summary>
/// <param name="jobList"></param>
/// <returns></returns>
private List<Job> ApplyTimeFiltering(List<Job> jobList)
{
bool beforeParameter = MyInvocation.BoundParameters.ContainsKey("Before");
bool afterParameter = MyInvocation.BoundParameters.ContainsKey("After");
bool newestParameter = MyInvocation.BoundParameters.ContainsKey("Newest");
if (!beforeParameter && !afterParameter && !newestParameter)
{
return jobList;
}
// Apply filtering.
List<Job> filteredJobs;
if (beforeParameter || afterParameter)
{
filteredJobs = new List<Job>();
foreach (Job job in jobList)
{
if (job.PSEndTime == DateTime.MinValue)
{
// Skip invalid dates.
continue;
}
if (beforeParameter && afterParameter)
{
if (job.PSEndTime < Before &&
job.PSEndTime > After)
{
filteredJobs.Add(job);
}
}
else if ((beforeParameter &&
job.PSEndTime < Before) ||
(afterParameter &&
job.PSEndTime > After))
{
filteredJobs.Add(job);
}
}
}
else
{
filteredJobs = jobList;
}
if (!newestParameter ||
filteredJobs.Count == 0)
{
return filteredJobs;
}
//
// Apply Newest count.
//
// Sort filtered jobs
filteredJobs.Sort((firstJob, secondJob) =>
{
if (firstJob.PSEndTime > secondJob.PSEndTime)
{
return -1;
}
else if (firstJob.PSEndTime < secondJob.PSEndTime)
{
return 1;
}
else
{
return 0;
}
});
List<Job> newestJobs = new List<Job>();
int count = 0;
foreach (Job job in filteredJobs)
{
if (++count > Newest)
{
break;
}
if (!newestJobs.Contains(job))
{
newestJobs.Add(job);
}
}
return newestJobs;
}
#endregion Private Members
}
}
| |
using System;
using NBitcoin.BouncyCastle.Security;
namespace NBitcoin.BouncyCastle.Crypto.Paddings
{
/**
* A wrapper class that allows block ciphers to be used to process data in
* a piecemeal fashion with padding. The PaddedBufferedBlockCipher
* outputs a block only when the buffer is full and more data is being added,
* or on a doFinal (unless the current block in the buffer is a pad block).
* The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
*/
internal class PaddedBufferedBlockCipher
: BufferedBlockCipher
{
private readonly IBlockCipherPadding padding;
/**
* Create a buffered block cipher with the desired padding.
*
* @param cipher the underlying block cipher this buffering object wraps.
* @param padding the padding type.
*/
public PaddedBufferedBlockCipher(
IBlockCipher cipher,
IBlockCipherPadding padding)
{
this.cipher = cipher;
this.padding = padding;
this.buf = new byte[cipher.GetBlockSize()];
this.bufOff = 0;
}
/**
* Create a buffered block cipher Pkcs7 padding
*
* @param cipher the underlying block cipher this buffering object wraps.
*/
public PaddedBufferedBlockCipher(
IBlockCipher cipher)
: this(cipher, new Pkcs7Padding()) { }
/**
* initialise the cipher.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public override void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
SecureRandom initRandom = null;
Reset();
this.padding.Init(initRandom);
this.cipher.Init(forEncryption, parameters);
}
/**
* return the minimum size of the output buffer required for an update
* plus a doFinal with an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update and doFinal
* with len bytes of input.
*/
public override int GetOutputSize(
int length)
{
int total = length + this.bufOff;
int leftOver = total % this.buf.Length;
if(leftOver == 0)
{
if(this.forEncryption)
{
return total + this.buf.Length;
}
return total;
}
return total - leftOver + this.buf.Length;
}
/**
* return the size of the output buffer required for an update
* an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update
* with len bytes of input.
*/
public override int GetUpdateOutputSize(
int length)
{
int total = length + this.bufOff;
int leftOver = total % this.buf.Length;
if(leftOver == 0)
{
return total - this.buf.Length;
}
return total - leftOver;
}
/**
* process a single byte, producing an output block if necessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessByte(
byte input,
byte[] output,
int outOff)
{
int resultLen = 0;
if(this.bufOff == this.buf.Length)
{
resultLen = this.cipher.ProcessBlock(this.buf, 0, output, outOff);
this.bufOff = 0;
}
this.buf[this.bufOff++] = input;
return resultLen;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param len the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessBytes(
byte[] input,
int inOff,
int length,
byte[] output,
int outOff)
{
if(length < 0)
{
throw new ArgumentException("Can't have a negative input length!");
}
int blockSize = GetBlockSize();
int outLength = GetUpdateOutputSize(length);
if(outLength > 0)
{
Check.OutputLength(output, outOff, outLength, "output buffer too short");
}
int resultLen = 0;
int gapLen = this.buf.Length - this.bufOff;
if(length > gapLen)
{
Array.Copy(input, inOff, this.buf, this.bufOff, gapLen);
resultLen += this.cipher.ProcessBlock(this.buf, 0, output, outOff);
this.bufOff = 0;
length -= gapLen;
inOff += gapLen;
while(length > this.buf.Length)
{
resultLen += this.cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
length -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, this.buf, this.bufOff, length);
this.bufOff += length;
return resultLen;
}
/**
* Process the last block in the buffer. If the buffer is currently
* full and padding needs to be added a call to doFinal will produce
* 2 * GetBlockSize() bytes.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there is insufficient space in out for
* the output or we are decrypting and the input is not block size aligned.
* @exception InvalidOperationException if the underlying cipher is not
* initialised.
* @exception InvalidCipherTextException if padding is expected and not found.
*/
public override int DoFinal(
byte[] output,
int outOff)
{
int blockSize = this.cipher.GetBlockSize();
int resultLen = 0;
if(this.forEncryption)
{
if(this.bufOff == blockSize)
{
if((outOff + 2 * blockSize) > output.Length)
{
Reset();
throw new OutputLengthException("output buffer too short");
}
resultLen = this.cipher.ProcessBlock(this.buf, 0, output, outOff);
this.bufOff = 0;
}
this.padding.AddPadding(this.buf, this.bufOff);
resultLen += this.cipher.ProcessBlock(this.buf, 0, output, outOff + resultLen);
Reset();
}
else
{
if(this.bufOff == blockSize)
{
resultLen = this.cipher.ProcessBlock(this.buf, 0, this.buf, 0);
this.bufOff = 0;
}
else
{
Reset();
throw new DataLengthException("last block incomplete in decryption");
}
try
{
resultLen -= this.padding.PadCount(this.buf);
Array.Copy(this.buf, 0, output, outOff, resultLen);
}
finally
{
Reset();
}
}
return resultLen;
}
}
}
| |
using System;
using System.Globalization;
namespace System
{
internal static class SR
{
public static string Arg_ArrayZeroError
{
get { return Environment.GetResourceString("Arg_ArrayZeroError"); }
}
public static string Arg_HexStyleNotSupported
{
get { return Environment.GetResourceString("Arg_HexStyleNotSupported"); }
}
public static string Arg_InvalidHexStyle
{
get { return Environment.GetResourceString("Arg_InvalidHexStyle"); }
}
public static string ArgumentNull_Array
{
get { return Environment.GetResourceString("ArgumentNull_Array"); }
}
public static string ArgumentNull_ArrayValue
{
get { return Environment.GetResourceString("ArgumentNull_ArrayValue"); }
}
public static string ArgumentNull_Obj
{
get { return Environment.GetResourceString("ArgumentNull_Obj"); }
}
public static string ArgumentNull_String
{
get { return Environment.GetResourceString("ArgumentNull_String"); }
}
public static string ArgumentOutOfRange_AddValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_AddValue"); }
}
public static string ArgumentOutOfRange_BadHourMinuteSecond
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); }
}
public static string ArgumentOutOfRange_BadYearMonthDay
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); }
}
public static string ArgumentOutOfRange_Bounds_Lower_Upper
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); }
}
public static string ArgumentOutOfRange_CalendarRange
{
get { return Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"); }
}
public static string ArgumentOutOfRange_Count
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Count"); }
}
public static string ArgumentOutOfRange_Day
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Day"); }
}
public static string ArgumentOutOfRange_Enum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Enum"); }
}
public static string ArgumentOutOfRange_Era
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Era"); }
}
public static string ArgumentOutOfRange_Index
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Index"); }
}
public static string ArgumentOutOfRange_InvalidEraValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"); }
}
public static string ArgumentOutOfRange_Month
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Month"); }
}
public static string ArgumentOutOfRange_NeedNonNegNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); }
}
public static string ArgumentOutOfRange_NeedPosNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"); }
}
public static string Arg_ArgumentOutOfRangeException
{
get { return Environment.GetResourceString("Arg_ArgumentOutOfRangeException"); }
}
public static string ArgumentOutOfRange_OffsetLength
{
get { return Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"); }
}
public static string ArgumentOutOfRange_Range
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Range"); }
}
public static string Argument_CompareOptionOrdinal
{
get { return Environment.GetResourceString("Argument_CompareOptionOrdinal"); }
}
public static string Argument_ConflictingDateTimeRoundtripStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); }
}
public static string Argument_ConflictingDateTimeStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeStyles"); }
}
public static string Argument_CultureIetfNotSupported
{
get { return Environment.GetResourceString("Argument_CultureIetfNotSupported"); }
}
public static string Argument_CultureInvalidIdentifier
{
get { return Environment.GetResourceString("Argument_CultureInvalidIdentifier"); }
}
public static string Argument_CultureNotSupported
{
get { return Environment.GetResourceString("Argument_CultureNotSupported"); }
}
public static string Argument_CultureIsNeutral
{
get { return Environment.GetResourceString("Argument_CultureIsNeutral"); }
}
public static string Argument_CustomCultureCannotBePassedByNumber
{
get { return Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber"); }
}
public static string Argument_EmptyDecString
{
get { return Environment.GetResourceString("Argument_EmptyDecString"); }
}
public static string Argument_InvalidArrayLength
{
get { return Environment.GetResourceString("Argument_InvalidArrayLength"); }
}
public static string Argument_InvalidCalendar
{
get { return Environment.GetResourceString("Argument_InvalidCalendar"); }
}
public static string Argument_InvalidCultureName
{
get { return Environment.GetResourceString("Argument_InvalidCultureName"); }
}
public static string Argument_InvalidDateTimeStyles
{
get { return Environment.GetResourceString("Argument_InvalidDateTimeStyles"); }
}
public static string Argument_InvalidDigitSubstitution
{
get { return Environment.GetResourceString("Argument_InvalidDigitSubstitution"); }
}
public static string Argument_InvalidFlag
{
get { return Environment.GetResourceString("Argument_InvalidFlag"); }
}
public static string Argument_InvalidGroupSize
{
get { return Environment.GetResourceString("Argument_InvalidGroupSize"); }
}
public static string Argument_InvalidNativeDigitCount
{
get { return Environment.GetResourceString("Argument_InvalidNativeDigitCount"); }
}
public static string Argument_InvalidNativeDigitValue
{
get { return Environment.GetResourceString("Argument_InvalidNativeDigitValue"); }
}
public static string Argument_InvalidNeutralRegionName
{
get { return Environment.GetResourceString("Argument_InvalidNeutralRegionName"); }
}
public static string Argument_InvalidNumberStyles
{
get { return Environment.GetResourceString("Argument_InvalidNumberStyles"); }
}
public static string Argument_InvalidResourceCultureName
{
get { return Environment.GetResourceString("Argument_InvalidResourceCultureName"); }
}
public static string Argument_NoEra
{
get { return Environment.GetResourceString("Argument_NoEra"); }
}
public static string Argument_NoRegionInvariantCulture
{
get { return Environment.GetResourceString("Argument_NoRegionInvariantCulture"); }
}
public static string Argument_OneOfCulturesNotSupported
{
get { return Environment.GetResourceString("Argument_OneOfCulturesNotSupported"); }
}
public static string Argument_OnlyMscorlib
{
get { return Environment.GetResourceString("Argument_OnlyMscorlib"); }
}
public static string Argument_ResultCalendarRange
{
get { return Environment.GetResourceString("Argument_ResultCalendarRange"); }
}
public static string Format_BadFormatSpecifier
{
get { return Environment.GetResourceString("Format_BadFormatSpecifier"); }
}
public static string InvalidOperation_DateTimeParsing
{
get { return Environment.GetResourceString("InvalidOperation_DateTimeParsing"); }
}
public static string InvalidOperation_EnumEnded
{
get { return Environment.GetResourceString("InvalidOperation_EnumEnded"); }
}
public static string InvalidOperation_EnumNotStarted
{
get { return Environment.GetResourceString("InvalidOperation_EnumNotStarted"); }
}
public static string InvalidOperation_ReadOnly
{
get { return Environment.GetResourceString("InvalidOperation_ReadOnly"); }
}
public static string Overflow_TimeSpanTooLong
{
get { return Environment.GetResourceString("Overflow_TimeSpanTooLong"); }
}
public static string Serialization_MemberOutOfRange
{
get { return Environment.GetResourceString("Serialization_MemberOutOfRange"); }
}
public static string Arg_InvalidHandle
{
get { return Environment.GetResourceString("Arg_InvalidHandle"); }
}
public static string ObjectDisposed_FileClosed
{
get { return Environment.GetResourceString("ObjectDisposed_FileClosed"); }
}
public static string Arg_HandleNotAsync
{
get { return Environment.GetResourceString("Arg_HandleNotAsync"); }
}
public static string ArgumentNull_Path
{
get { return Environment.GetResourceString("ArgumentNull_Path"); }
}
public static string Argument_EmptyPath
{
get { return Environment.GetResourceString("Argument_EmptyPath"); }
}
public static string Argument_InvalidFileModeAndAccessCombo
{
get { return Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo"); }
}
public static string Argument_InvalidAppendMode
{
get { return Environment.GetResourceString("Argument_InvalidAppendMode"); }
}
public static string ArgumentNull_Buffer
{
get { return Environment.GetResourceString("ArgumentNull_Buffer"); }
}
public static string Argument_InvalidOffLen
{
get { return Environment.GetResourceString("Argument_InvalidOffLen"); }
}
public static string IO_UnknownFileName
{
get { return Environment.GetResourceString("IO_UnknownFileName"); }
}
public static string IO_FileStreamHandlePosition
{
get { return Environment.GetResourceString("IO.IO_FileStreamHandlePosition"); }
}
public static string NotSupported_FileStreamOnNonFiles
{
get { return Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"); }
}
public static string IO_BindHandleFailed
{
get { return Environment.GetResourceString("IO.IO_BindHandleFailed"); }
}
public static string Arg_HandleNotSync
{
get { return Environment.GetResourceString("Arg_HandleNotSync"); }
}
public static string IO_SetLengthAppendTruncate
{
get { return Environment.GetResourceString("IO.IO_SetLengthAppendTruncate"); }
}
public static string ArgumentOutOfRange_FileLengthTooBig
{
get { return Environment.GetResourceString("ArgumentOutOfRange_FileLengthTooBig"); }
}
public static string Argument_InvalidSeekOrigin
{
get { return Environment.GetResourceString("Argument_InvalidSeekOrigin"); }
}
public static string IO_SeekAppendOverwrite
{
get { return Environment.GetResourceString("IO.IO_SeekAppendOverwrite"); }
}
public static string IO_FileTooLongOrHandleNotSync
{
get { return Environment.GetResourceString("IO_FileTooLongOrHandleNotSync"); }
}
public static string IndexOutOfRange_IORaceCondition
{
get { return Environment.GetResourceString("IndexOutOfRange_IORaceCondition"); }
}
public static string IO_FileNotFound
{
get { return Environment.GetResourceString("IO.FileNotFound"); }
}
public static string IO_FileNotFound_FileName
{
get { return Environment.GetResourceString("IO.FileNotFound_FileName"); }
}
public static string IO_PathNotFound_NoPathName
{
get { return Environment.GetResourceString("IO.PathNotFound_NoPathName"); }
}
public static string IO_PathNotFound_Path
{
get { return Environment.GetResourceString("IO.PathNotFound_Path"); }
}
public static string UnauthorizedAccess_IODenied_NoPathName
{
get { return Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"); }
}
public static string UnauthorizedAccess_IODenied_Path
{
get { return Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"); }
}
public static string IO_AlreadyExists_Name
{
get { return Environment.GetResourceString("IO.IO_AlreadyExists_Name"); }
}
public static string IO_PathTooLong
{
get { return Environment.GetResourceString("IO.PathTooLong"); }
}
public static string IO_SharingViolation_NoFileName
{
get { return Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"); }
}
public static string IO_SharingViolation_File
{
get { return Environment.GetResourceString("IO.IO_SharingViolation_File"); }
}
public static string IO_FileExists_Name
{
get { return Environment.GetResourceString("IO.IO_FileExists_Name"); }
}
public static string NotSupported_UnwritableStream
{
get { return Environment.GetResourceString("NotSupported_UnwritableStream"); }
}
public static string NotSupported_UnreadableStream
{
get { return Environment.GetResourceString("NotSupported_UnreadableStream"); }
}
public static string NotSupported_UnseekableStream
{
get { return Environment.GetResourceString("NotSupported_UnseekableStream"); }
}
public static string IO_EOF_ReadBeyondEOF
{
get { return Environment.GetResourceString("IO.EOF_ReadBeyondEOF"); }
}
public static string Argument_InvalidHandle
{
get { return Environment.GetResourceString("Argument_InvalidHandle"); }
}
public static string Argument_AlreadyBoundOrSyncHandle
{
get { return Environment.GetResourceString("Argument_AlreadyBoundOrSyncHandle"); }
}
public static string Argument_PreAllocatedAlreadyAllocated
{
get { return Environment.GetResourceString("Argument_PreAllocatedAlreadyAllocated"); }
}
public static string Argument_NativeOverlappedAlreadyFree
{
get { return Environment.GetResourceString("Argument_NativeOverlappedAlreadyFree"); }
}
public static string Argument_NativeOverlappedWrongBoundHandle
{
get { return Environment.GetResourceString("Argument_NativeOverlappedWrongBoundHandle"); }
}
public static string InvalidOperation_NativeOverlappedReused
{
get { return Environment.GetResourceString("InvalidOperation_NativeOverlappedReused"); }
}
public static string ArgumentException_BufferNotFromPool
{
get { return Environment.GetResourceString("ArgumentException_BufferNotFromPool"); }
}
public static string Format(string formatString, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, formatString, args);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Cassette.Caching;
using Cassette.HtmlTemplates;
using Cassette.Scripts;
using Cassette.Stylesheets;
using Cassette.TinyIoC;
#if NET35
using System.Reflection.Emit;
#endif
namespace Cassette
{
/// <summary>
/// A host initializes Cassette for an application.
/// </summary>
public abstract class HostBase : IDisposable
{
TinyIoCContainer container;
Type[] allTypes;
Type[] configurationTypes;
AssemblyScanner assemblyScanner;
public void Initialize()
{
var assemblies = LoadAssemblies();
assemblyScanner = new AssemblyScanner(assemblies);
allTypes = assemblyScanner.GetAllTypes();
configurationTypes = GetConfigurationTypes(allTypes).ToArray();
container = new TinyIoCContainer();
ConfigureContainer();
RunStartUpTasks();
InitializeBundles();
}
protected TinyIoCContainer Container
{
get
{
if (container == null) throw new InvalidOperationException("Container is not available before Initialize has been called.");
return container;
}
}
/// <summary>
/// Loads and returns all the assemblies used by the application. These will be scanned for Cassette types.
/// </summary>
protected abstract IEnumerable<Assembly> LoadAssemblies();
/// <summary>
/// Returns all types that implement <see cref="IConfiguration{T}"/>.
/// </summary>
protected virtual IEnumerable<Type> GetConfigurationTypes(IEnumerable<Type> typesToSearch)
{
var publicTypes =
from type in typesToSearch
where type.IsClass && !type.IsAbstract
from interfaceType in type.GetInterfaces()
where interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IConfiguration<>)
select type;
var internalTypes = new[]
{
typeof(ScriptContainerConfiguration),
typeof(StylesheetsContainerConfiguration),
typeof(HtmlTemplatesContainerConfiguration),
typeof(SettingsVersionAssigner)
};
return publicTypes.Concat(internalTypes);
}
protected virtual void ConfigureContainer()
{
// REGISTER ALL THE THINGS!
RegisterBundleCollection();
RegisterUrlGenerator();
RegisterCache();
RegisterBundleCollectionInitializer();
RegisterStartUpTasks();
RegisterSettings();
RegisterBundleFactoryProvider();
RegisterFileSearchProvider();
RegisterFileAccessAuthorization();
RegisterPerRequestServices();
RegisterConfigurationTypes();
RegisterJsonSerializer();
// Classes that implement IConfiguration<TinyIoCContainer> can register services in the container.
// This means plugins and the application can add to and override Cassette's default services.
ExecuteContainerConfigurations();
}
void RegisterBundleCollection()
{
container.Register(typeof(BundleCollection)).AsSingleton();
}
void RegisterUrlGenerator()
{
container.Register<IUrlGenerator>((c, n) => new UrlGenerator(c.Resolve<IUrlModifier>(), "cassette.axd/"));
}
void RegisterCache()
{
container.Register<IBundleCollectionCache>((c, p) =>
{
var cacheDirectory = c.Resolve<CassetteSettings>().CacheDirectory;
return new BundleCollectionCache(
cacheDirectory,
bundleTypeName => ResolveBundleDeserializer(bundleTypeName, c)
);
});
container.Register((c, p) =>
{
Func<Type, IAssetCacheValidator> assetCacheValidatorFactory = type => (IAssetCacheValidator)c.Resolve(type);
var sourceDirectory = c.Resolve<CassetteSettings>().SourceDirectory;
return new ManifestValidator(assetCacheValidatorFactory, sourceDirectory);
});
container.Register((c, p) =>
{
var sourceDirectory = c.Resolve<CassetteSettings>().SourceDirectory;
return new FileAssetCacheValidator(sourceDirectory);
});
container.Register(typeof(IBundleCacheRebuilder), typeof(BundleCacheRebuilder));
}
static readonly Dictionary<string, Type> BundleDeserializers = new Dictionary<string, Type>
{
{ typeof(ScriptBundle).Name, typeof(ScriptBundleDeserializer) },
{ typeof(StylesheetBundle).Name, typeof(StylesheetBundleDeserializer) },
{ typeof(HtmlTemplateBundle).Name, typeof(HtmlTemplateBundleDeserializer) },
{ typeof(ExternalScriptBundle).Name, typeof(ExternalScriptBundleDeserializer) },
{ typeof(ExternalStylesheetBundle).Name, typeof(ExternalStylesheetBundleDeserializer) }
};
internal static IBundleDeserializer<Bundle> ResolveBundleDeserializer(string bundleTypeName, TinyIoCContainer container)
{
var deserializerType = BundleDeserializers[bundleTypeName];
return (IBundleDeserializer<Bundle>)container.Resolve(deserializerType);
}
protected virtual void RegisterBundleCollectionInitializer()
{
container.Register<IBundleCollectionInitializer>(
(c, p) => new ExceptionCatchingBundleCollectionInitializer(
c.Resolve<RuntimeBundleCollectionInitializer>()
)
);
}
void RegisterStartUpTasks()
{
container.RegisterMultiple(typeof(IStartUpTask), GetStartUpTaskTypes());
}
void RegisterSettings()
{
// Host specific settings configuration is named so that it's included when CassetteSettings asks for IEnumerable<IConfiguration<CassetteSettings>>.
container.Register(CreateHostSpecificSettingsConfiguration(), "HostSpecificSettingsConfiguration");
container.Register(typeof(CassetteSettings)).AsSingleton();
}
protected abstract IConfiguration<CassetteSettings> CreateHostSpecificSettingsConfiguration();
void RegisterBundleFactoryProvider()
{
container.Register(
typeof(IBundleFactoryProvider),
(c, p) => new BundleFactoryProvider(
bundleType =>
{
var factoryType = typeof(IBundleFactory<>).MakeGenericType(bundleType);
return (IBundleFactory<Bundle>)c.Resolve(factoryType);
}
)
);
}
void RegisterFileSearchProvider()
{
container.Register(
typeof(IFileSearchProvider),
(c, p) => new FileSearchProvider(
bundleType => c.Resolve<IFileSearch>(FileSearchComponentName(bundleType))
)
);
}
void RegisterFileAccessAuthorization()
{
container.Register<IFileAccessAuthorization, FileAccessAuthorization>().AsSingleton();
}
void RegisterPerRequestServices()
{
if (!CanCreateRequestLifetimeProvider) return;
container
.Register(typeof(IReferenceBuilder), typeof(ReferenceBuilder))
.AsPerRequestSingleton(CreateRequestLifetimeProvider());
container
.Register(typeof(PlaceholderTracker))
.AsPerRequestSingleton(CreateRequestLifetimeProvider());
container.
Register(typeof(IPlaceholderTracker), (c, p) => CreatePlaceholderTracker(c));
}
protected abstract bool CanCreateRequestLifetimeProvider { get; }
protected virtual TinyIoCContainer.ITinyIoCObjectLifetimeProvider CreateRequestLifetimeProvider()
{
throw new NotSupportedException();
}
void ExecuteContainerConfigurations()
{
var containerConfigurations = CreateContainerConfigurations();
foreach (var containerConfiguration in containerConfigurations)
{
containerConfiguration.Configure(container);
}
}
IEnumerable<IConfiguration<TinyIoCContainer>> CreateContainerConfigurations()
{
return
from type in configurationTypes
where typeof(IConfiguration<TinyIoCContainer>).IsAssignableFrom(type)
orderby ConfigurationOrderAttribute.GetOrder(type)
select CreateContainerConfiguration(type);
}
IConfiguration<TinyIoCContainer> CreateContainerConfiguration(Type configurationC)
{
var ctor = configurationC.GetConstructors().First();
var isDefaultConstructor = ctor.GetParameters().Length == 0;
if (isDefaultConstructor)
{
return (IConfiguration<TinyIoCContainer>)Activator.CreateInstance(configurationC);
}
else
{
// Special hack for the bundle container configurations.
// They take the GetImplementationTypes delegate.
var args = new object[] { new Func<Type, IEnumerable<Type>>(GetImplementationTypes) };
return (IConfiguration<TinyIoCContainer>)ctor.Invoke(args);
}
}
void RegisterConfigurationTypes()
{
var configurations =
from type in configurationTypes
from interfaceType in type.GetInterfaces()
where interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IConfiguration<>) &&
interfaceType != typeof(IConfiguration<TinyIoCContainer>) // These have already been created and used.
select new
{
registrationType = interfaceType,
implementationType = type
};
var groupedByRegistrationType = configurations.GroupBy(
c => c.registrationType,
c => c.implementationType
);
foreach (var configs in groupedByRegistrationType)
{
var registrationType = configs.Key;
var implementationTypes = configs;
container.RegisterMultiple(registrationType, implementationTypes);
}
}
void RegisterJsonSerializer()
{
container.Register<IJsonSerializer, SimpleJsonSerializer>();
}
IEnumerable<Type> GetImplementationTypes(Type baseType)
{
return allTypes.Where(baseType.IsAssignableFrom);
}
IPlaceholderTracker CreatePlaceholderTracker(TinyIoCContainer currentContainer)
{
if (currentContainer.Resolve<CassetteSettings>().IsHtmlRewritingEnabled)
{
return currentContainer.Resolve<PlaceholderTracker>();
}
else
{
return new NullPlaceholderTracker();
}
}
protected virtual IEnumerable<Type> GetStartUpTaskTypes()
{
return GetImplementationTypes(typeof(IStartUpTask));
}
void InitializeBundles()
{
var builder = container.Resolve<IBundleCollectionInitializer>();
var bundles = container.Resolve<BundleCollection>();
builder.Initialize(bundles);
}
void RunStartUpTasks()
{
var startUpTasks = container.ResolveAll<IStartUpTask>();
foreach (var startUpTask in startUpTasks)
{
Trace.Source.TraceInformation("Running start-up task: {0}", startUpTask.GetType().FullName);
startUpTask.Start();
}
}
/// <summary>
/// A separate <see cref="IFileSearch"/> is stored in the container for each type of bundle.
/// This method returns a name that identifies the FileSearch for a particular bundle type.
/// </summary>
internal static string FileSearchComponentName(Type bundleType)
{
return bundleType.Name + ".FileSearch";
}
public virtual void Dispose()
{
var local = container;
if (local != null)
{
local.Dispose();
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G10_City (editable child object).<br/>
/// This is a generated base class of <see cref="G10_City"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="G11_CityRoadObjects"/> of type <see cref="G11_CityRoadColl"/> (1:M relation to <see cref="G12_CityRoad"/>)<br/>
/// This class is an item of <see cref="G09_CityColl"/> collection.
/// </remarks>
[Serializable]
public partial class G10_City : BusinessBase<G10_City>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID");
/// <summary>
/// Gets the Cities ID.
/// </summary>
/// <value>The Cities ID.</value>
public int City_ID
{
get { return GetProperty(City_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="City_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name");
/// <summary>
/// Gets or sets the Cities Name.
/// </summary>
/// <value>The Cities Name.</value>
public string City_Name
{
get { return GetProperty(City_NameProperty); }
set { SetProperty(City_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G11_City_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G11_City_Child> G11_City_SingleObjectProperty = RegisterProperty<G11_City_Child>(p => p.G11_City_SingleObject, "G11 City Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G11 City Single Object ("self load" child property).
/// </summary>
/// <value>The G11 City Single Object.</value>
public G11_City_Child G11_City_SingleObject
{
get { return GetProperty(G11_City_SingleObjectProperty); }
private set { LoadProperty(G11_City_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G11_City_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G11_City_ReChild> G11_City_ASingleObjectProperty = RegisterProperty<G11_City_ReChild>(p => p.G11_City_ASingleObject, "G11 City ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G11 City ASingle Object ("self load" child property).
/// </summary>
/// <value>The G11 City ASingle Object.</value>
public G11_City_ReChild G11_City_ASingleObject
{
get { return GetProperty(G11_City_ASingleObjectProperty); }
private set { LoadProperty(G11_City_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G11_CityRoadObjects"/> property.
/// </summary>
public static readonly PropertyInfo<G11_CityRoadColl> G11_CityRoadObjectsProperty = RegisterProperty<G11_CityRoadColl>(p => p.G11_CityRoadObjects, "G11 CityRoad Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the G11 City Road Objects ("self load" child property).
/// </summary>
/// <value>The G11 City Road Objects.</value>
public G11_CityRoadColl G11_CityRoadObjects
{
get { return GetProperty(G11_CityRoadObjectsProperty); }
private set { LoadProperty(G11_CityRoadObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G10_City"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G10_City"/> object.</returns>
internal static G10_City NewG10_City()
{
return DataPortal.CreateChild<G10_City>();
}
/// <summary>
/// Factory method. Loads a <see cref="G10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="G10_City"/> object.</returns>
internal static G10_City GetG10_City(SafeDataReader dr)
{
G10_City obj = new G10_City();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G10_City"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G10_City()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G10_City"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(G11_City_SingleObjectProperty, DataPortal.CreateChild<G11_City_Child>());
LoadProperty(G11_City_ASingleObjectProperty, DataPortal.CreateChild<G11_City_ReChild>());
LoadProperty(G11_CityRoadObjectsProperty, DataPortal.CreateChild<G11_CityRoadColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_IDProperty, dr.GetInt32("City_ID"));
LoadProperty(City_NameProperty, dr.GetString("City_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(G11_City_SingleObjectProperty, G11_City_Child.GetG11_City_Child(City_ID));
LoadProperty(G11_City_ASingleObjectProperty, G11_City_ReChild.GetG11_City_ReChild(City_ID));
LoadProperty(G11_CityRoadObjectsProperty, G11_CityRoadColl.GetG11_CityRoadColl(City_ID));
}
/// <summary>
/// Inserts a new <see cref="G10_City"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Region_ID", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(City_IDProperty, (int) cmd.Parameters["@City_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G10_City"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="G10_City"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteG10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(G11_City_SingleObjectProperty, DataPortal.CreateChild<G11_City_Child>());
LoadProperty(G11_City_ASingleObjectProperty, DataPortal.CreateChild<G11_City_ReChild>());
LoadProperty(G11_CityRoadObjectsProperty, DataPortal.CreateChild<G11_CityRoadColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#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.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
namespace System.Collections.Immutable
{
/// <summary>
/// A readonly array with O(1) indexable lookup time.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <devremarks>
/// This type has a documented contract of being exactly one reference-type field in size.
/// Our own <see cref="ImmutableInterlocked"/> class depends on it, as well as others externally.
/// IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:
/// This type should be thread-safe. As a struct, it cannot protect its own fields
/// from being changed from one thread while its members are executing on other threads
/// because structs can change *in place* simply by reassigning the field containing
/// this struct. Therefore it is extremely important that
/// ** Every member should only dereference <c>this</c> ONCE. **
/// If a member needs to reference the array field, that counts as a dereference of <c>this</c>.
/// Calling other instance members (properties or methods) also counts as dereferencing <c>this</c>.
/// Any member that needs to use <c>this</c> more than once must instead
/// assign <c>this</c> to a local variable and use that for the rest of the code instead.
/// This effectively copies the one field in the struct to a local variable so that
/// it is insulated from other threads.
/// </devremarks>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[NonVersionable] // Applies to field layout
public partial struct ImmutableArray<T> : IEnumerable<T>, IEquatable<ImmutableArray<T>>, IImmutableArray
{
/// <summary>
/// An empty (initialized) instance of <see cref="ImmutableArray{T}"/>.
/// </summary>
public static readonly ImmutableArray<T> Empty = new ImmutableArray<T>(new T[0]);
/// <summary>
/// The backing field for this instance. References to this value should never be shared with outside code.
/// </summary>
/// <remarks>
/// This would be private, but we make it internal so that our own extension methods can access it.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal T[] array;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct
/// *without making a defensive copy*.
/// </summary>
/// <param name="items">The array to use. May be null for "default" arrays.</param>
internal ImmutableArray(T[] items)
{
this.array = items;
}
#region Operators
/// <summary>
/// Checks equality between two instances.
/// </summary>
/// <param name="left">The instance to the left of the operator.</param>
/// <param name="right">The instance to the right of the operator.</param>
/// <returns><c>true</c> if the values' underlying arrays are reference equal; <c>false</c> otherwise.</returns>
[NonVersionable]
public static bool operator ==(ImmutableArray<T> left, ImmutableArray<T> right)
{
return left.Equals(right);
}
/// <summary>
/// Checks inequality between two instances.
/// </summary>
/// <param name="left">The instance to the left of the operator.</param>
/// <param name="right">The instance to the right of the operator.</param>
/// <returns><c>true</c> if the values' underlying arrays are reference not equal; <c>false</c> otherwise.</returns>
[NonVersionable]
public static bool operator !=(ImmutableArray<T> left, ImmutableArray<T> right)
{
return !left.Equals(right);
}
/// <summary>
/// Checks equality between two instances.
/// </summary>
/// <param name="left">The instance to the left of the operator.</param>
/// <param name="right">The instance to the right of the operator.</param>
/// <returns><c>true</c> if the values' underlying arrays are reference equal; <c>false</c> otherwise.</returns>
public static bool operator ==(ImmutableArray<T>? left, ImmutableArray<T>? right)
{
return left.GetValueOrDefault().Equals(right.GetValueOrDefault());
}
/// <summary>
/// Checks inequality between two instances.
/// </summary>
/// <param name="left">The instance to the left of the operator.</param>
/// <param name="right">The instance to the right of the operator.</param>
/// <returns><c>true</c> if the values' underlying arrays are reference not equal; <c>false</c> otherwise.</returns>
public static bool operator !=(ImmutableArray<T>? left, ImmutableArray<T>? right)
{
return !left.GetValueOrDefault().Equals(right.GetValueOrDefault());
}
#endregion
/// <summary>
/// Gets the element at the specified index in the read-only list.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <returns>The element at the specified index in the read-only list.</returns>
public T this[int index]
{
[NonVersionable]
get
{
// We intentionally do not check this.array != null, and throw NullReferenceException
// if this is called while uninitialized.
// The reason for this is perf.
// Length and the indexer must be absolutely trivially implemented for the JIT optimization
// of removing array bounds checking to work.
return this.array[index];
}
}
/// <summary>
/// Gets a value indicating whether this collection is empty.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public bool IsEmpty
{
[NonVersionable]
get { return this.Length == 0; }
}
/// <summary>
/// Gets the number of elements in the array.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Length
{
[NonVersionable]
get
{
// We intentionally do not check this.array != null, and throw NullReferenceException
// if this is called while uninitialized.
// The reason for this is perf.
// Length and the indexer must be absolutely trivially implemented for the JIT optimization
// of removing array bounds checking to work.
return this.array.Length;
}
}
/// <summary>
/// Gets a value indicating whether this struct was initialized without an actual array instance.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public bool IsDefault
{
get { return this.array == null; }
}
/// <summary>
/// Gets a value indicating whether this struct is empty or uninitialized.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public bool IsDefaultOrEmpty
{
get
{
var self = this;
return self.array == null || self.array.Length == 0;
}
}
/// <summary>
/// Gets an untyped reference to the array.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Array IImmutableArray.Array
{
get { return this.array; }
}
/// <summary>
/// Gets the string to display in the debugger watches window for this instance.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string DebuggerDisplay
{
get
{
var self = this;
return self.IsDefault ? "Uninitialized" : String.Format(CultureInfo.CurrentCulture, "Length = {0}", self.Length);
}
}
/// <summary>
/// Copies the contents of this array to the specified array.
/// </summary>
/// <param name="destination">The array to copy to.</param>
[Pure]
public void CopyTo(T[] destination)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Array.Copy(self.array, 0, destination, 0, self.Length);
}
/// <summary>
/// Copies the contents of this array to the specified array.
/// </summary>
/// <param name="destination">The array to copy to.</param>
/// <param name="destinationIndex">The index into the destination array to which the first copied element is written.</param>
[Pure]
public void CopyTo(T[] destination, int destinationIndex)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Array.Copy(self.array, 0, destination, destinationIndex, self.Length);
}
/// <summary>
/// Copies the contents of this array to the specified array.
/// </summary>
/// <param name="sourceIndex">The index into this collection of the first element to copy.</param>
/// <param name="destination">The array to copy to.</param>
/// <param name="destinationIndex">The index into the destination array to which the first copied element is written.</param>
/// <param name="length">The number of elements to copy.</param>
[Pure]
public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Array.Copy(self.array, sourceIndex, destination, destinationIndex, length);
}
/// <summary>
/// Returns a builder that is populated with the same contents as this array.
/// </summary>
/// <returns>The new builder.</returns>
[Pure]
public ImmutableArray<T>.Builder ToBuilder()
{
var self = this;
if (self.Length == 0)
{
return new Builder(); // allow the builder to create itself with a reasonable default capacity
}
var builder = new Builder(self.Length);
builder.AddRange(self);
return builder;
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
[Pure]
public Enumerator GetEnumerator()
{
var self = this;
self.ThrowNullRefIfNotInitialized();
return new Enumerator(self.array);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
[Pure]
public override int GetHashCode()
{
var self = this;
return self.array == null ? 0 : self.array.GetHashCode();
}
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
[Pure]
public override bool Equals(object obj)
{
IImmutableArray other = obj as IImmutableArray;
if (other != null)
{
return this.array == other.Array;
}
return false;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
[Pure]
[NonVersionable]
public bool Equals(ImmutableArray<T> other)
{
return this.array == other.array;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct based on the contents
/// of an existing instance, allowing a covariant static cast to efficiently reuse the existing array.
/// </summary>
/// <param name="items">The array to initialize the array with. No copy is made.</param>
/// <remarks>
/// Covariant upcasts from this method may be reversed by calling the
/// <see cref="ImmutableArray{T}.As{TOther}"/> or <see cref="ImmutableArray{T}.CastArray{TOther}"/>method.
/// </remarks>
[Pure]
public static ImmutableArray<T> CastUp<TDerived>(ImmutableArray<TDerived> items)
where TDerived : class, T
{
return new ImmutableArray<T>(items.array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct by casting the underlying
/// array to an array of type <typeparam name="TOther"/>.
/// </summary>
/// <exception cref="InvalidCastException">Thrown if the cast is illegal.</exception>
[Pure]
public ImmutableArray<TOther> CastArray<TOther>() where TOther : class
{
return new ImmutableArray<TOther>((TOther[])(object)array);
}
/// <summary>
/// Creates an immutable array for this array, cast to a different element type.
/// </summary>
/// <typeparam name="TOther">The type of array element to return.</typeparam>
/// <returns>
/// A struct typed for the base element type. If the cast fails, an instance
/// is returned whose <see cref="IsDefault"/> property returns <c>true</c>.
/// </returns>
/// <remarks>
/// Arrays of derived elements types can be cast to arrays of base element types
/// without reallocating the array.
/// These upcasts can be reversed via this same method, casting an array of base
/// element types to their derived types. However, downcasting is only successful
/// when it reverses a prior upcasting operation.
/// </remarks>
[Pure]
public ImmutableArray<TOther> As<TOther>() where TOther : class
{
return new ImmutableArray<TOther>(this.array as TOther[]);
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return EnumeratorObject.Create(self.array);
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return EnumeratorObject.Create(self.array);
}
/// <summary>
/// Throws a null reference exception if the array field is null.
/// </summary>
internal void ThrowNullRefIfNotInitialized()
{
// Force NullReferenceException if array is null by touching its Length.
// This way of checking has a nice property of requiring very little code
// and not having any conditions/branches.
// In a faulting scenario we are relying on hardware to generate the fault.
// And in the non-faulting scenario (most common) the check is virtually free since
// if we are going to do anything with the array, we will need Length anyways
// so touching it, and potentially causing a cache miss, is not going to be an
// extra expense.
var unused = this.array.Length;
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if the <see cref="array"/> field is null, i.e. the
/// <see cref="IsDefault"/> property returns true. The
/// <see cref="InvalidOperationException"/> message specifies that the operation cannot be performed
/// on a default instance of <see cref="ImmutableArray{T}"/>.
///
/// This is intended for explicitly implemented interface method and property implementations.
/// </summary>
private void ThrowInvalidOperationIfNotInitialized()
{
if (this.IsDefault)
{
throw new InvalidOperationException(SR.InvalidOperationOnDefaultArray);
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using Belikov.GenuineChannels.BufferPooling;
namespace Belikov.GenuineChannels.GenuineUdp
{
/// <summary>
/// Represents a stream being assembled from UDP packets.
/// </summary>
public class StreamAssembled : Stream, IDisposable
{
/// <summary>
/// Constructs an instance of the StreamAssembled class.
/// </summary>
/// <param name="remoteIPEndPoint">The IPEndPoint of the sender.</param>
/// <param name="headerSize">The size of the header.</param>
public StreamAssembled(IPEndPoint remoteIPEndPoint, int headerSize)
{
this._started = GenuineUtility.TickCount;
this.RemoteIPEndPoint = remoteIPEndPoint;
this._headerSize = headerSize;
this._readPosition = headerSize;
}
/// <summary>
/// To guarantee atomic access to local members.
/// </summary>
private object _accessToLocalMembers = new object();
/// <summary>
/// The moment when the first chunk was received.
/// </summary>
public int Started
{
get
{
lock (this._accessToLocalMembers)
return this._started;
}
}
private int _started;
/// <summary>
/// The received content.
/// </summary>
public ArrayList _chunks = new ArrayList();
/// <summary>
/// The IPEndPoint of the remote host.
/// </summary>
public IPEndPoint RemoteIPEndPoint;
/// <summary>
/// Gets or sets an indication whether the message has been already processed.
/// </summary>
public bool IsProcessed
{
get
{
lock (this)
return this._isProcessed;
}
set
{
lock (this)
this._isProcessed = value;
}
}
private bool _isProcessed;
/// <summary>
/// The size of the header in the provided chunks.
/// </summary>
private int _headerSize;
/// <summary>
/// True if the last packet was received.
/// </summary>
private bool _wasLastPacketReceived;
/// <summary>
/// Local variable indicated whether stream has been disposed.
/// </summary>
private bool _disposed = false;
/// <summary>
/// Puts the received buffer into the chunk store.
/// </summary>
/// <param name="chunkNumber">The sequence number of the current chunk.</param>
/// <param name="buffer">The chunk.</param>
/// <param name="size">The size of valid content.</param>
/// <param name="isLast">Whether it is the last packet in the sequence.</param>
/// <returns>True if the stream is gathered.</returns>
public bool BufferReceived(int chunkNumber, byte[] buffer, int size, bool isLast)
{
if (isLast)
this._wasLastPacketReceived = true;
// fill it up to make up the sequence
while (this._chunks.Count < chunkNumber * 2 + 1)
{
this._chunks.Add(null);
this._chunks.Add(0);
}
// update the sequence
if (0 == (int) this._chunks[chunkNumber * 2 + 1])
{
this._chunks[chunkNumber * 2] = buffer;
this._chunks[chunkNumber * 2 + 1] = size;
}
// check whether all chunks are gathered
if (! this._wasLastPacketReceived)
return false;
for ( int i = 0; i < this._chunks.Count / 2; i++)
if (0 == (int) this._chunks[i * 2 + 1] )
return false;
return true;
}
#region -- Reading -------------------------------------------------------------------------
private int _readBlockNumber = 0;
private int _readPosition;
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (this._disposed)
throw new ObjectDisposedException("GenuineChunkedStream");
int totalReadBytes = 0;
for ( ; ; )
{
if (this._readBlockNumber >= this._chunks.Count || count <= 0)
return totalReadBytes;
// locate the next available buffer
byte[] sourceBuffer = (byte[]) this._chunks[this._readBlockNumber];
int sourceBufferSize = (int) this._chunks[this._readBlockNumber + 1];
// if the current buffer has been read, move pointer to the next one
if (sourceBufferSize <= this._readPosition)
{
BufferPool.RecycleBuffer(sourceBuffer);
this._chunks.RemoveRange(0, 2);
this._readPosition = this._headerSize;
continue;
}
int readLen = Math.Min(count, sourceBufferSize - this._readPosition);
Buffer.BlockCopy(sourceBuffer, this._readPosition, buffer, offset, readLen);
offset += readLen;
count -= readLen;
totalReadBytes += readLen;
this._readPosition += readLen;
}
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
if (this._disposed)
throw new ObjectDisposedException("GenuineChunkedStream");
for ( ; ; )
{
if (this._readBlockNumber >= this._chunks.Count)
return -1;
// locate the next available buffer
byte[] sourceBuffer = (byte[]) this._chunks[this._readBlockNumber];
int sourceBufferSize = (int) this._chunks[this._readBlockNumber + 1];
// if the current buffer has been read, move the pointer to the next one
if (sourceBufferSize <= this._readPosition)
{
BufferPool.RecycleBuffer(sourceBuffer);
this._chunks.RemoveRange(0, 2);
this._readPosition = this._headerSize;
continue;
}
return sourceBuffer[this._readPosition ++];
}
}
/// <summary>
/// Closes the current stream and releases any resources associated with the current stream.
/// </summary>
public new void Dispose()
{
this.Close();
}
/// <summary>
/// Closes the current stream and releases any resources associated with the current stream.
/// </summary>
public override void Close()
{
if (this._disposed)
return ;
for ( int i = 0; i < this._chunks.Count; i += 2)
{
byte[] buffer = (byte[]) this._chunks[i];
BufferPool.RecycleBuffer(buffer);
}
this._chunks.Clear();
this._disposed = true;
}
#endregion
#region -- Insignificant stream members ----------------------------------------------------
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return false;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// Always fires NotSupportedException exception.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Begins an asynchronous read operation.
/// </summary>
/// <param name="buffer">The buffer to read the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Begins an asynchronous write operation.
/// </summary>
/// <param name="buffer">The buffer to write data from.</param>
/// <param name="offset">The byte offset in buffer from which to begin writing.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous write, which could still be pending.</returns>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Waits for the pending asynchronous read to complete.
/// </summary>
/// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
/// <returns>The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams only return zero (0) at the end of the stream, otherwise, they should block until at least one byte is available.</returns>
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Ends an asynchronous write operation.
/// </summary>
/// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="val">The desired length of the current stream in bytes.</param>
public override void SetLength(long val)
{
throw new NotSupportedException();
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Lucene.Net.Search
{
using Lucene.Net.Support;
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
/// <summary>
/// A Scorer for OR like queries, counterpart of <code>ConjunctionScorer</code>.
/// this Scorer implements <seealso cref="Scorer#advance(int)"/> and uses advance() on the given Scorers.
///
/// this implementation uses the minimumMatch constraint actively to efficiently
/// prune the number of candidates, it is hence a mixture between a pure DisjunctionScorer
/// and a ConjunctionScorer.
/// </summary>
internal class MinShouldMatchSumScorer : Scorer
{
/// <summary>
/// The overall number of non-finalized scorers </summary>
private int NumScorers;
/// <summary>
/// The minimum number of scorers that should match </summary>
private readonly int Mm;
/// <summary>
/// A static array of all subscorers sorted by decreasing cost </summary>
private readonly Scorer[] SortedSubScorers;
/// <summary>
/// A monotonically increasing index into the array pointing to the next subscorer that is to be excluded </summary>
private int SortedSubScorersIdx = 0;
private readonly Scorer[] SubScorers; // the first numScorers-(mm-1) entries are valid
private int NrInHeap; // 0..(numScorers-(mm-1)-1)
/// <summary>
/// mmStack is supposed to contain the most costly subScorers that still did
/// not run out of docs, sorted by increasing sparsity of docs returned by that subScorer.
/// For now, the cost of subscorers is assumed to be inversely correlated with sparsity.
/// </summary>
private readonly Scorer[] MmStack; // of size mm-1: 0..mm-2, always full
/// <summary>
/// The document number of the current match. </summary>
private int Doc = -1;
/// <summary>
/// The number of subscorers that provide the current match. </summary>
protected internal int NrMatchers = -1;
private double Score_Renamed = float.NaN;
/// <summary>
/// Construct a <code>MinShouldMatchSumScorer</code>.
/// </summary>
/// <param name="weight"> The weight to be used. </param>
/// <param name="subScorers"> A collection of at least two subscorers. </param>
/// <param name="minimumNrMatchers"> The positive minimum number of subscorers that should
/// match to match this query.
/// <br>When <code>minimumNrMatchers</code> is bigger than
/// the number of <code>subScorers</code>, no matches will be produced.
/// <br>When minimumNrMatchers equals the number of subScorers,
/// it is more efficient to use <code>ConjunctionScorer</code>. </param>
public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers, int minimumNrMatchers)
: base(weight)
{
this.NrInHeap = this.NumScorers = subScorers.Count;
if (minimumNrMatchers <= 0)
{
throw new System.ArgumentException("Minimum nr of matchers must be positive");
}
if (NumScorers <= 1)
{
throw new System.ArgumentException("There must be at least 2 subScorers");
}
this.Mm = minimumNrMatchers;
this.SortedSubScorers = subScorers.ToArray();
// sorting by decreasing subscorer cost should be inversely correlated with
// next docid (assuming costs are due to generating many postings)
ArrayUtil.TimSort(SortedSubScorers, new ComparatorAnonymousInnerClassHelper(this));
// take mm-1 most costly subscorers aside
this.MmStack = new Scorer[Mm - 1];
for (int i = 0; i < Mm - 1; i++)
{
MmStack[i] = SortedSubScorers[i];
}
NrInHeap -= Mm - 1;
this.SortedSubScorersIdx = Mm - 1;
// take remaining into heap, if any, and heapify
this.SubScorers = new Scorer[NrInHeap];
for (int i = 0; i < NrInHeap; i++)
{
this.SubScorers[i] = this.SortedSubScorers[Mm - 1 + i];
}
MinheapHeapify();
Debug.Assert(MinheapCheck());
}
private class ComparatorAnonymousInnerClassHelper : IComparer<Scorer>
{
private readonly MinShouldMatchSumScorer OuterInstance;
public ComparatorAnonymousInnerClassHelper(MinShouldMatchSumScorer outerInstance)
{
this.OuterInstance = outerInstance;
}
public virtual int Compare(Scorer o1, Scorer o2)
{
return Number.Signum(o2.Cost() - o1.Cost());
}
}
/// <summary>
/// Construct a <code>DisjunctionScorer</code>, using one as the minimum number
/// of matching subscorers.
/// </summary>
public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers)
: this(weight, subScorers, 1)
{
}
public override sealed ICollection<ChildScorer> Children
{
get
{
List<ChildScorer> children = new List<ChildScorer>(NumScorers);
for (int i = 0; i < NumScorers; i++)
{
children.Add(new ChildScorer(SubScorers[i], "SHOULD"));
}
return children;
}
}
public override int NextDoc()
{
Debug.Assert(Doc != NO_MORE_DOCS);
while (true)
{
// to remove current doc, call next() on all subScorers on current doc within heap
while (SubScorers[0].DocID() == Doc)
{
if (SubScorers[0].NextDoc() != NO_MORE_DOCS)
{
MinheapSiftDown(0);
}
else
{
MinheapRemoveRoot();
NumScorers--;
if (NumScorers < Mm)
{
return Doc = NO_MORE_DOCS;
}
}
//assert minheapCheck();
}
EvaluateSmallestDocInHeap();
if (NrMatchers >= Mm) // doc satisfies mm constraint
{
break;
}
}
return Doc;
}
private void EvaluateSmallestDocInHeap()
{
// within heap, subScorer[0] now contains the next candidate doc
Doc = SubScorers[0].DocID();
if (Doc == NO_MORE_DOCS)
{
NrMatchers = int.MaxValue; // stop looping
return;
}
// 1. score and count number of matching subScorers within heap
Score_Renamed = SubScorers[0].Score();
NrMatchers = 1;
CountMatches(1);
CountMatches(2);
// 2. score and count number of matching subScorers within stack,
// short-circuit: stop when mm can't be reached for current doc, then perform on heap next()
// TODO instead advance() might be possible, but complicates things
for (int i = Mm - 2; i >= 0; i--) // first advance sparsest subScorer
{
if (MmStack[i].DocID() >= Doc || MmStack[i].Advance(Doc) != NO_MORE_DOCS)
{
if (MmStack[i].DocID() == Doc) // either it was already on doc, or got there via advance()
{
NrMatchers++;
Score_Renamed += MmStack[i].Score();
} // scorer advanced to next after doc, check if enough scorers left for current doc
else
{
if (NrMatchers + i < Mm) // too few subScorers left, abort advancing
{
return; // continue looping TODO consider advance() here
}
}
} // subScorer exhausted
else
{
NumScorers--;
if (NumScorers < Mm) // too few subScorers left
{
Doc = NO_MORE_DOCS;
NrMatchers = int.MaxValue; // stop looping
return;
}
if (Mm - 2 - i > 0)
{
// shift RHS of array left
Array.Copy(MmStack, i + 1, MmStack, i, Mm - 2 - i);
}
// find next most costly subScorer within heap TODO can this be done better?
while (!MinheapRemove(SortedSubScorers[SortedSubScorersIdx++]))
{
//assert minheapCheck();
}
// add the subScorer removed from heap to stack
MmStack[Mm - 2] = SortedSubScorers[SortedSubScorersIdx - 1];
if (NrMatchers + i < Mm) // too few subScorers left, abort advancing
{
return; // continue looping TODO consider advance() here
}
}
}
}
// TODO: this currently scores, but so did the previous impl
// TODO: remove recursion.
// TODO: consider separating scoring out of here, then modify this
// and afterNext() to terminate when nrMatchers == minimumNrMatchers
// then also change freq() to just always compute it from scratch
private void CountMatches(int root)
{
if (root < NrInHeap && SubScorers[root].DocID() == Doc)
{
NrMatchers++;
Score_Renamed += SubScorers[root].Score();
CountMatches((root << 1) + 1);
CountMatches((root << 1) + 2);
}
}
/// <summary>
/// Returns the score of the current document matching the query. Initially
/// invalid, until <seealso cref="#nextDoc()"/> is called the first time.
/// </summary>
public override float Score()
{
return (float)Score_Renamed;
}
public override int DocID()
{
return Doc;
}
public override int Freq()
{
return NrMatchers;
}
/// <summary>
/// Advances to the first match beyond the current whose document number is
/// greater than or equal to a given target. <br>
/// The implementation uses the advance() method on the subscorers.
/// </summary>
/// <param name="target"> the target document number. </param>
/// <returns> the document whose number is greater than or equal to the given
/// target, or -1 if none exist. </returns>
public override int Advance(int target)
{
if (NumScorers < Mm)
{
return Doc = NO_MORE_DOCS;
}
// advance all Scorers in heap at smaller docs to at least target
while (SubScorers[0].DocID() < target)
{
if (SubScorers[0].Advance(target) != NO_MORE_DOCS)
{
MinheapSiftDown(0);
}
else
{
MinheapRemoveRoot();
NumScorers--;
if (NumScorers < Mm)
{
return Doc = NO_MORE_DOCS;
}
}
//assert minheapCheck();
}
EvaluateSmallestDocInHeap();
if (NrMatchers >= Mm)
{
return Doc;
}
else
{
return NextDoc();
}
}
public override long Cost()
{
// cost for merging of lists analog to DisjunctionSumScorer
long costCandidateGeneration = 0;
for (int i = 0; i < NrInHeap; i++)
{
costCandidateGeneration += SubScorers[i].Cost();
}
// TODO is cost for advance() different to cost for iteration + heap merge
// and how do they compare overall to pure disjunctions?
const float c1 = 1.0f, c2 = 1.0f; // maybe a constant, maybe a proportion between costCandidateGeneration and sum(subScorer_to_be_advanced.cost())?
return (long)(c1 * costCandidateGeneration + c2 * costCandidateGeneration * (Mm - 1)); // advance() cost - heap-merge cost
}
/// <summary>
/// Organize subScorers into a min heap with scorers generating the earliest document on top.
/// </summary>
protected internal void MinheapHeapify()
{
for (int i = (NrInHeap >> 1) - 1; i >= 0; i--)
{
MinheapSiftDown(i);
}
}
/// <summary>
/// The subtree of subScorers at root is a min heap except possibly for its root element.
/// Bubble the root down as required to make the subtree a heap.
/// </summary>
protected internal void MinheapSiftDown(int root)
{
// TODO could this implementation also move rather than swapping neighbours?
Scorer scorer = SubScorers[root];
int doc = scorer.DocID();
int i = root;
while (i <= (NrInHeap >> 1) - 1)
{
int lchild = (i << 1) + 1;
Scorer lscorer = SubScorers[lchild];
int ldoc = lscorer.DocID();
int rdoc = int.MaxValue, rchild = (i << 1) + 2;
Scorer rscorer = null;
if (rchild < NrInHeap)
{
rscorer = SubScorers[rchild];
rdoc = rscorer.DocID();
}
if (ldoc < doc)
{
if (rdoc < ldoc)
{
SubScorers[i] = rscorer;
SubScorers[rchild] = scorer;
i = rchild;
}
else
{
SubScorers[i] = lscorer;
SubScorers[lchild] = scorer;
i = lchild;
}
}
else if (rdoc < doc)
{
SubScorers[i] = rscorer;
SubScorers[rchild] = scorer;
i = rchild;
}
else
{
return;
}
}
}
protected internal void MinheapSiftUp(int i)
{
Scorer scorer = SubScorers[i];
int doc = scorer.DocID();
// find right place for scorer
while (i > 0)
{
int parent = (i - 1) >> 1;
Scorer pscorer = SubScorers[parent];
int pdoc = pscorer.DocID();
if (pdoc > doc) // move root down, make space
{
SubScorers[i] = SubScorers[parent];
i = parent;
} // done, found right place
else
{
break;
}
}
SubScorers[i] = scorer;
}
/// <summary>
/// Remove the root Scorer from subScorers and re-establish it as a heap
/// </summary>
protected internal void MinheapRemoveRoot()
{
if (NrInHeap == 1)
{
//subScorers[0] = null; // not necessary
NrInHeap = 0;
}
else
{
NrInHeap--;
SubScorers[0] = SubScorers[NrInHeap];
//subScorers[nrInHeap] = null; // not necessary
MinheapSiftDown(0);
}
}
/// <summary>
/// Removes a given Scorer from the heap by placing end of heap at that
/// position and bubbling it either up or down
/// </summary>
protected internal bool MinheapRemove(Scorer scorer)
{
// find scorer: O(nrInHeap)
for (int i = 0; i < NrInHeap; i++)
{
if (SubScorers[i] == scorer) // remove scorer
{
SubScorers[i] = SubScorers[--NrInHeap];
//if (i != nrInHeap) subScorers[nrInHeap] = null; // not necessary
MinheapSiftUp(i);
MinheapSiftDown(i);
return true;
}
}
return false; // scorer already exhausted
}
internal virtual bool MinheapCheck()
{
return MinheapCheck(0);
}
private bool MinheapCheck(int root)
{
if (root >= NrInHeap)
{
return true;
}
int lchild = (root << 1) + 1;
int rchild = (root << 1) + 2;
if (lchild < NrInHeap && SubScorers[root].DocID() > SubScorers[lchild].DocID())
{
return false;
}
if (rchild < NrInHeap && SubScorers[root].DocID() > SubScorers[rchild].DocID())
{
return false;
}
return MinheapCheck(lchild) && MinheapCheck(rchild);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace System.Reflection
{
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Runtime.CompilerServices;
public sealed class AssemblyName
{
private Assembly _assembly;
//--//
internal AssemblyName(Assembly assm)
{
_assembly = assm;
}
public String Name
{
get
{
return _assembly.FullName.Substring(0, _assembly.FullName.IndexOf(','));
}
}
public String FullName
{
get
{
return _assembly.FullName;
}
}
public Version Version
{
get
{
int major = -1, minor = -1, build = -1, revision = -1;
_assembly.GetVersion(ref major, ref minor, ref build, ref revision);
return new Version(major, minor, build, revision);
}
}
}
[Serializable()]
[Clarity.ExportStub("System_Reflection_Assembly.cpp")]
public class Assembly
{
public extern virtual String FullName
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static Assembly GetExecutingAssembly();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void GetVersion(ref int major, ref int minor, ref int build, ref int revision);
public AssemblyName GetName()
{
return new AssemblyName(this);
}
public static Assembly GetAssembly(Type type)
{
return type.Assembly;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Type GetType(String name);
public virtual Type GetType(String name, bool throwOnError)
{
Type type = GetType(name);
if (type == null)
{
throw new ArgumentException();
}
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Type[] GetTypes();
public Assembly GetSatelliteAssembly(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException("culture");
}
Assembly assm = null;
string baseName = this.FullName;
string cultureName;
while (assm == null && (cultureName = culture.Name) != "")
{
string assmName = baseName + "." + cultureName;
assm = Assembly.Load(assmName, false);
culture = culture.Parent;
}
if (assm == null)
{
throw new ArgumentException();
// FIXME -- throw new FileNotFoundException();
}
return assm;
}
public static Assembly Load(String assemblyString)
{
if (assemblyString == null)
{
throw new ArgumentNullException("assemblyString");
}
return Load(assemblyString, true);
}
internal static string ParseAssemblyName(String assemblyString, ref bool fVersion, ref int[] ver)
{
// valid names are in the forms:
// 1) "Microsoft.SPOT.Native" or
// 2) "Microsoft.SPOT.Native, Version=1.2.3.4" or
// 3) "Microsoft.SPOT.Native.resources, Version=1.2.3.4" or
// 4) "Microsoft.SPOT.Native.tinyresources, Version=1.2.3.4"
// 5) (FROM THE DEBUGGER) "Microsoft.SPOT.Native, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null[, ...]
int versionIdx, commaIdx;
string name;
fVersion = false;
// if there is no comma then we have an assembly name in the form with no version
if ((commaIdx = assemblyString.IndexOf(',')) != -1)
{
name = assemblyString.Substring(0, commaIdx);
const string c_versionTag = "version=";
// verify that the format with the version is correct and skip the ", Version=" part of the string
if ((versionIdx = assemblyString.ToLower().IndexOf(c_versionTag)) != 0)
{
fVersion = true;
// the "version=" string must come right after the ' ,'
if (versionIdx == commaIdx + 2)
{
int startIdx = versionIdx + c_versionTag.Length;
int endIdx;
// trim off the Culture, PublicKeyToken, etc for now
if(-1 != (endIdx = assemblyString.IndexOf(',', startIdx)))
{
assemblyString = assemblyString.Substring(startIdx, endIdx - startIdx);
}
else
{
assemblyString = assemblyString.Substring(startIdx);
}
// at this point we have assemblyString = "1.2.3.4"
string[] version = assemblyString.Split('.');
if (version.Length > 0) ver[0] = UInt16.Parse(version[0]);
if (version.Length > 1) ver[1] = UInt16.Parse(version[1]);
// build and revision versions may be -1 (which means "don't care")
if (version.Length > 2) ver[2] = int.Parse(version[2]);
if (version.Length > 3) ver[3] = int.Parse(version[3]);
}
else
{
throw new ArgumentException();
}
}
else
{
throw new ArgumentException();
}
}
else
{
name = assemblyString;
}
return name;
}
internal static Assembly Load(String assemblyString, bool fThrowOnError)
{
bool fVersion = false;
int[] ver = new int[4];
string name = ParseAssemblyName(assemblyString, ref fVersion, ref ver);
Assembly assm = LoadInternal(name, fVersion, ver[0], ver[1], ver[2], ver[3]);
if (assm == null)
{
if (fThrowOnError)
{
// FIXME -- should be FileNotFoundException, per spec.
throw new ArgumentException();
}
}
return assm;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Assembly LoadInternal(String assemblyString, bool fVersion, int maj, int min, int build, int rev);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern public Assembly Load(byte[] rawAssembly);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String[] GetManifestResourceNames();
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Your favorite String class. Native methods
** are implemented in StringNative.cpp
**
**
===========================================================*/
namespace System
{
using System.Text;
using System;
using System.Buffers;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics;
using System.Security;
//
// For Information on these methods, please see COMString.cpp
//
// The String class represents a static string of characters. Many of
// the String methods perform some type of transformation on the current
// instance and return the result as a new String. All comparison methods are
// implemented as a part of String. As with arrays, character positions
// (indices) are zero-based.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable
, IComparable<String>, IEnumerable<char>, IEquatable<String>
{
//
//NOTE NOTE NOTE NOTE
//These fields map directly onto the fields in an EE StringObject. See object.h for the layout.
//
[NonSerialized] private int m_stringLength;
// For empty strings, this will be '\0' since
// strings are both null-terminated and length prefixed
[NonSerialized] private char _firstChar;
// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
//
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;
internal char FirstChar { get { return _firstChar; } }
//
// This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less
// than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's)
// from the assembly. This provides a workaround for that problem and should NOT be used anywhere else.
//
internal unsafe static string SmallCharToUpper(string strIn)
{
Debug.Assert(strIn != null);
//
// Get the length and pointers to each of the buffers. Walk the length
// of the string and copy the characters from the inBuffer to the outBuffer,
// capitalizing it if necessary. We assert that all of our characters are
// less than 0x80.
//
int length = strIn.Length;
String strOut = FastAllocateString(length);
fixed (char* inBuff = &strIn._firstChar, outBuff = &strOut._firstChar)
{
for (int i = 0; i < length; i++)
{
int c = inBuff[i];
Debug.Assert(c <= 0x7F, "string has to be ASCII");
// uppercase - notice that we need just one compare
if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
outBuff[i] = (char)c;
}
Debug.Assert(outBuff[length] == '\0', "outBuff[length]=='\0'");
}
return strOut;
}
// Gets the character at a specified position.
//
[System.Runtime.CompilerServices.IndexerName("Chars")]
public extern char this[int index]
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
// Note: fixed does not like empty arrays
if (count > 0)
{
fixed (char* src = &_firstChar)
fixed (char* dest = destination)
wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
}
// Returns the entire string as an array of characters.
unsafe public char[] ToCharArray()
{
int length = Length;
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src, length);
}
return chars;
}
return Array.Empty<char>();
}
// Returns a substring of this string as an array of characters.
//
unsafe public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src + startIndex, length);
}
return chars;
}
return Array.Empty<char>();
}
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
if (!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
// Gets the length of this string
//
/// This is a EE implemented function so that the JIT can recognise is specially
/// and eliminate checks on character fetchs in a loop like:
/// for(int i = 0; i < str.Length; i++) str[i]
/// The actually code generated for this will be one instruction and will be inlined.
//
public extern int Length
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
//
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char* value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value, int startIndex, int length, Encoding enc);
unsafe static private String CreateString(sbyte* value, int startIndex, int length, Encoding enc)
{
if (enc == null)
return new String(value, startIndex, length); // default to ANSI
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if ((value + startIndex) < value)
{
// overflow check
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
byte[] b = new byte[length];
try
{
Buffer.Memcpy(b, 0, (byte*)value, startIndex, length);
}
catch (NullReferenceException)
{
// If we got a NullReferencException. It means the pointer or
// the index is out of range
throw new ArgumentOutOfRangeException(nameof(value),
SR.ArgumentOutOfRange_PartialWCHAR);
}
return enc.GetString(b);
}
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
unsafe static internal String CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Debug.Assert(bytes != null);
Debug.Assert(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return String.Empty;
String s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s._firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since _firstChar is a private member.
// Making _firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result._firstChar = c;
return result;
}
unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer, Encoding encoding)
{
// encoding == Encoding.UTF8
fixed (char* pwzChar = &_firstChar)
{
return encoding.GetBytes(pwzChar, m_stringLength, pbNativeBuffer, cbNativeBuffer);
}
}
unsafe internal int ConvertToAnsi(byte* pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
const uint CP_ACP = 0;
int nb;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = (fBestFit ? 0 : WC_NO_BEST_FIT_CHARS);
uint DefaultCharUsed = 0;
fixed (char* pwzChar = &_firstChar)
{
nb = Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
pwzChar,
this.Length,
pbNativeBuffer,
cbNativeBuffer,
IntPtr.Zero,
(fThrowOnUnmappableChar ? new IntPtr(&DefaultCharUsed) : IntPtr.Zero));
}
if (0 != DefaultCharUsed)
{
throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char);
}
pbNativeBuffer[nb] = 0;
return nb;
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
// Default to Form C
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return true;
}
return Normalization.IsNormalized(this, normalizationForm);
}
public String Normalize()
{
// Default to Form C
return Normalize(NormalizationForm.FormC);
}
public String Normalize(NormalizationForm normalizationForm)
{
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return this;
}
return Normalization.Normalize(this, normalizationForm);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String FastAllocateString(int length);
// Creates a new string from the characters in a subarray. The new string will
// be created from the characters in value between startIndex and
// startIndex + length - 1.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value, int startIndex, int length);
// Creates a new string from the characters in a subarray. The new string will be
// created from the characters in value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value);
internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
}
private String CtorCharArray(char[] value)
{
if (value != null && value.Length != 0)
{
String result = FastAllocateString(value.Length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
{
wstrcpy(dest, source, value.Length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharArrayStartLength(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length > 0)
{
String result = FastAllocateString(length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
{
wstrcpy(dest, source + startIndex, length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharCount(char c, int count)
{
if (count > 0)
{
String result = FastAllocateString(count);
if (c != 0)
{
unsafe
{
fixed (char* dest = &result._firstChar)
{
char* dmem = dest;
while (((uint)dmem & 3) != 0 && count > 0)
{
*dmem++ = c;
count--;
}
uint cc = (uint)((c << 16) | c);
if (count >= 4)
{
count -= 4;
do
{
((uint*)dmem)[0] = cc;
((uint*)dmem)[1] = cc;
dmem += 4;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0)
{
((uint*)dmem)[0] = cc;
dmem += 2;
}
if ((count & 1) != 0)
dmem[0] = c;
}
}
}
return result;
}
else if (count == 0)
return String.Empty;
else
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(count)));
}
internal static unsafe int wcslen(char* ptr)
{
char* end = ptr;
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
// If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way
while (((uint)end & (uint)alignment) != 0)
{
if (*end == 0) goto FoundZero;
end++;
}
#if !BIT64
// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.
// The loop condition below works because if "end[0] & end[1]" is non-zero, that means
// neither operand can have been zero. If is zero, we have to look at the operands individually,
// but we hope this going to fairly rare.
// In general, it would be incorrect to access end[1] if we haven't made sure
// end[0] is non-zero. However, we know the ptr has been aligned by the loop above
// so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not.
while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) {
end += 2;
}
Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
// 64-bit implementation: process 1 ulong (word) at a time
// What we do here is add 0x7fff from each of the
// 4 individual chars within the ulong, using MagicMask.
// If the char > 0 and < 0x8001, it will have its high bit set.
// We then OR with MagicMask, to set all the other bits.
// This will result in all bits set (ulong.MaxValue) for any
// char that fits the above criteria, and something else otherwise.
// Note that for any char > 0x8000, this will be a false
// positive and we will fallback to the slow path and
// check each char individually. This is OK though, since
// we optimize for the common case (ASCII chars, which are < 0x80).
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
{
ulong word = *(ulong*)end;
word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000
word |= MagicMask; // set everything besides the high bits
if (word == ulong.MaxValue) // 0xffff...
{
// all of the chars have their bits set (and therefore none can be 0)
end += 4;
continue;
}
// at least one of them didn't have their high bit set!
// go through each char and check for 0.
if (end[0] == 0) goto EndAt0;
if (end[1] == 0) goto EndAt1;
if (end[2] == 0) goto EndAt2;
if (end[3] == 0) goto EndAt3;
// if we reached here, it was a false positive-- just continue
end += 4;
}
EndAt3: end++;
EndAt2: end++;
EndAt1: end++;
EndAt0:
#endif // !BIT64
FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
return count;
}
private unsafe String CtorCharPtr(char* ptr)
{
if (ptr == null)
return String.Empty;
#if !FEATURE_PAL
if (ptr < (char*)64000)
throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom);
#endif // FEATURE_PAL
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
try
{
int count = wcslen(ptr);
if (count == 0)
return String.Empty;
String result = FastAllocateString(count);
fixed (char* dest = &result._firstChar)
wstrcpy(dest, ptr, count);
return result;
}
catch (NullReferenceException)
{
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
private unsafe String CtorCharPtrStartLength(char* ptr, int startIndex, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
char* pFrom = ptr + startIndex;
if (pFrom < ptr)
{
// This means that the pointer operation has had an overflow
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
if (length == 0)
return String.Empty;
String result = FastAllocateString(length);
try
{
fixed (char* dest = &result._firstChar)
wstrcpy(dest, pFrom, length);
return result;
}
catch (NullReferenceException)
{
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(ReadOnlySpan<char> value);
private unsafe string CtorReadOnlySpanOfChar(ReadOnlySpan<char> value)
{
if (value.Length == 0)
{
return Empty;
}
string result = FastAllocateString(value.Length);
fixed (char* dest = &result._firstChar, src = &MemoryMarshal.GetReference(value))
{
wstrcpy(dest, src, value.Length);
}
return result;
}
public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (length > 0)
{
string result = FastAllocateString(length);
action(new Span<char>(ref result.GetRawStringData(), length), state);
return result;
}
if (length == 0)
{
return Empty;
}
throw new ArgumentOutOfRangeException(nameof(length));
}
public static implicit operator ReadOnlySpan<char>(string value) =>
value != null ? new ReadOnlySpan<char>(ref value.GetRawStringData(), value.Length) : default;
// Returns this string.
public override String ToString()
{
return this;
}
public String ToString(IFormatProvider provider)
{
return this;
}
// Method required for the ICloneable interface.
// There's no point in cloning a string since they're immutable, so we simply return this.
public Object Clone()
{
return this;
}
unsafe public static String Copy(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int length = str.Length;
String result = FastAllocateString(length);
fixed (char* dest = &result._firstChar)
fixed (char* src = &str._firstChar)
{
wstrcpy(dest, src, length);
}
return result;
}
public static String Intern(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
return Thread.GetDomain().GetOrInternString(str);
}
public static String IsInterned(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
return Thread.GetDomain().IsStringInterned(str);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.String;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this, provider);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(this, provider);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this, provider);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this, provider);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this, provider);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this, provider);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this, provider);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this, provider);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this, provider);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this, provider);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this, provider);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(this, provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(this, provider);
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Is this a string that can be compared quickly (that is it has only characters > 0x80
// and not a - or '
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsFastSort();
// Is this a string that only contains characters < 0x80.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsAscii();
#if FEATURE_COMINTEROP
// Set extra byte for odd-sized strings that came from interop as BSTR.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetTrailByte(byte data);
// Try to retrieve the extra byte - returns false if not present.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool TryGetTrailByte(out byte data);
#endif
public CharEnumerator GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new CharEnumerator(this);
}
// Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
internal unsafe static void InternalCopy(String src, IntPtr dest, int len)
{
if (len == 0)
return;
fixed (char* charPtr = &src._firstChar)
{
byte* srcPtr = (byte*)charPtr;
byte* dstPtr = (byte*)dest;
Buffer.Memcpy(dstPtr, srcPtr, len);
}
}
internal ref char GetRawStringData()
{
return ref _firstChar;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using GerberParser.Commands;
using GerberParser.Commands.MacroPrimitives;
namespace GerberParser
{
public class GerberFileRender : IDisposable
{
private readonly Brush _activeBrush;
private readonly Brush _inactiveBrush;
private readonly Color _bgColor;
public GerberFileRender()
{
_activeBrush = new SolidBrush(Color.FromArgb(100, 0, 128, 0));
_bgColor = Color.FromArgb(0, 0, 0, 0);
_inactiveBrush = new SolidBrush(_bgColor);
}
public GerberFileRender(Color activeColor, Color inactiveColor)
{
_activeBrush = new SolidBrush(activeColor);
_bgColor = inactiveColor;
if (_bgColor.A == 255)
_inactiveBrush = new SolidBrush(_bgColor);
else
{
var color = Color.FromArgb(255, _bgColor.R, _bgColor.G, _bgColor.B);
_inactiveBrush = new SolidBrush(color);
}
}
private Brush GetBrushColor(bool isSolid)
{
return isSolid ? _activeBrush : _inactiveBrush; //Brushes.Green : Brushes.Black;
}
private const int MAX_IMG_SIZE = 20000;
public void CreateImage(GerberFileObject fileObject, decimal scale, string destFileName)
{
using (var img = CreateImageBitmap(fileObject, scale))
{
//img.RotateFlip(RotateFlipType.RotateNoneFlipX);
img.Save(destFileName, ImageFormat.Png);
}
}
public Bitmap CreateImageBitmap(GerberFileObject fileObject, decimal scale)
{
decimal minX, maxX, minY, maxY;
GerberFileProcessor.CalculateExtents(fileObject, out minX, out maxX, out minY, out maxY);
return CreateImageBitmap(fileObject, scale, minX, maxX, minY, maxY);
}
public Bitmap CreateImageBitmap(GerberFileObject fileObject, decimal scale, decimal minX, decimal maxX, decimal minY, decimal maxY)
{
//var border = fileObject.IsMetric ? 5.0m : 0.2m;
var border = 0m;
var offsetX = -minX;
var offsetY = -minY;
var state = new GraphicsState(scale, border, offsetX, offsetY);
state.Divisor = fileObject.Divisor;
var sizeX = (int)Math.Round((maxX - minX + border * 2) * scale);
var sizeY = (int)Math.Round((maxY - minY + border * 2) * scale);
if (sizeY > MAX_IMG_SIZE || sizeX > MAX_IMG_SIZE)
{
throw new Exception("ERROR - the image is too large, recude scale.");
}
Bitmap img;
try
{
img = new Bitmap(sizeX, sizeY);
}
catch (Exception)
{
throw new Exception("ERROR - the image is too large, recude scale.");
}
var gx = Graphics.FromImage(img);
gx.Clear(_bgColor);
state.GraphObject = gx;
foreach (var cmd in fileObject.Commands)
{
ProcessCommand(cmd as FormatStatementCommand, state);
ProcessCommand(cmd as ApertureDefinitionCommand, state);
ProcessCommand(cmd as ApertureMacroDefinitionCommand, state);
ProcessCommand(cmd as PolarityCommand, state);
ProcessCommand(cmd as LinearInterpolationCommand, state);
ProcessCommand(cmd as ClockwiseCircularInterpolationCommand, state);
ProcessCommand(cmd as CounterclockwiseCircularInterpolationCommand, state);
ProcessCommand(cmd as SingleQuadrantModeCommand, state);
ProcessCommand(cmd as MultiQuadrantModeCommand, state);
ProcessCommand(cmd as CurrentApertureCommand, state);
ProcessCommand(cmd as RegionBeginCommand, state);
ProcessCommand(cmd as RegionEndCommand, state);
ProcessCommand(cmd as OperationInterpolateCommand, state);
ProcessCommand(cmd as OperationMoveCommand, state);
ProcessCommand(cmd as OperationFlashCommand, state);
}
gx.Dispose();
return img;
}
private void ProcessCommand(FormatStatementCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IntPrecision = cmd.IntegerPositions;
state.DecPrecision = cmd.DecimalPositions;
}
private void ProcessCommand(ApertureDefinitionCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.Apertures.Add(cmd.Number, cmd);
}
private void ProcessCommand(ApertureMacroDefinitionCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.ApertureMacros.Add(cmd.Name, cmd);
}
private void ProcessCommand(PolarityCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IsDarkPolarity = cmd.IsDark;
}
private void ProcessCommand(LinearInterpolationCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.Interpolation = InterpolationMode.Linear;
}
private void ProcessCommand(ClockwiseCircularInterpolationCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.Interpolation = InterpolationMode.ClockwiseCircular;
}
private void ProcessCommand(CounterclockwiseCircularInterpolationCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.Interpolation = InterpolationMode.CounterclockwiseCircular;
}
private void ProcessCommand(SingleQuadrantModeCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IsMultiQuadrant = false;
}
private void ProcessCommand(MultiQuadrantModeCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IsMultiQuadrant = true;
}
private static void ProcessCommand(CurrentApertureCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.CurrentApertureNumber = cmd.Number;
}
private void ProcessCommand(RegionBeginCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IsInsideRegion = true;
}
private void ProcessCommand(RegionEndCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
state.IsInsideRegion = false;
DrawRegion(state);
}
private void DrawRegion(GraphicsState state)
{
if (state.CurrentRegion.PointCount == 0)
return;
//if (state.IsDarkPolarity)
//state.GraphObject.FillPolygon(GetBrushColor(state.IsDarkPolarity), state.CurrentRegion.ToArray());
state.GraphObject.FillPath(GetBrushColor(state.IsDarkPolarity), state.CurrentRegion);
state.CurrentRegion.Reset();
}
private Pen CreatePenForCurrentAperture(GraphicsState state)
{
var currAp = state.Apertures[state.CurrentApertureNumber];
Pen pen;
switch (currAp.Template)
{
case "C":
case "P":
pen = new Pen(GetBrushColor(state.IsDarkPolarity), (float)state.ScaleByRenderScale(currAp.Diameter));
break;
case "R":
case "O":
pen = new Pen(GetBrushColor(state.IsDarkPolarity),
(float)state.ScaleByRenderScale(Math.Max(currAp.SizeX, currAp.SizeY)));
break;
default:
pen = new Pen(GetBrushColor(state.IsDarkPolarity), 1);
break;
}
return pen;
}
private CoordinatePair FindCenterPoint(CoordinatePair beginPoint, CoordinatePair cmdPoint, OperationInterpolateCommand cmd, InterpolationMode mode)
{
var centerCandidates = new CoordinatePair[4];
centerCandidates[0] = new CoordinatePair
{
X = beginPoint.X - cmd.OffsetX,
Y = beginPoint.Y - cmd.OffsetY
};
centerCandidates[1] = new CoordinatePair
{
X = beginPoint.X - cmd.OffsetX,
Y = beginPoint.Y + cmd.OffsetY
};
centerCandidates[2] = new CoordinatePair
{
X = beginPoint.X + cmd.OffsetX,
Y = beginPoint.Y - cmd.OffsetY
};
centerCandidates[3] = new CoordinatePair
{
X = beginPoint.X + cmd.OffsetX,
Y = beginPoint.Y + cmd.OffsetY
};
foreach (var candidate in centerCandidates)
{
double angle = CalculateAngle(candidate, beginPoint, cmdPoint);
if (angle != 0.0 && (mode == InterpolationMode.ClockwiseCircular)
? (angle > 0.0)
: (angle < 0.0) && Math.Abs(angle) <= Math.PI / 2)
{
return candidate;
}
}
return null;
}
private void ProcessCommand(OperationInterpolateCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
var origPtX = cmd.HasX ? cmd.X : state.CurrentX;
var origPtY = cmd.HasY ? cmd.Y : state.CurrentY;
var pt = state.CalcCoords(origPtX, origPtY);
if (state.Interpolation == InterpolationMode.Linear)
{
var currPt = state.CalcCoordsForCurrentPoint();
if (state.IsInsideRegion)
{
state.CurrentRegion.AddLine(state.CalcCoordsForCurrentPoint(), pt);
}
else
{
using (var pen = CreatePenForCurrentAperture(state))
{
state.GraphObject.DrawLine(pen, currPt, pt);
DrawCurrentAperture(state, state.CurrentX, state.CurrentY);
DrawCurrentAperture(state, origPtX, origPtY);
}
}
}
else
{
CoordinatePair center;
Rectangle rect;
float angleF, sweep;
var cmdPoint = new CoordinatePair
{
X = origPtX,
Y = origPtY
};
var beginPoint = state.GetCurrentPoint();
if (!state.IsMultiQuadrant)
{
center = FindCenterPoint(beginPoint, cmdPoint, cmd, state.Interpolation);
}
else
{
center = new CoordinatePair
{
/*X = state.CurrentX + (state.Interpolation == InterpolationMode.ClockwiseCircular ? cmd.OffsetX : -cmd.OffsetX),
Y = state.CurrentY + (state.Interpolation == InterpolationMode.ClockwiseCircular ? cmd.OffsetY : -cmd.OffsetY)*/
X = state.CurrentX + cmd.OffsetX,
Y = state.CurrentY + cmd.OffsetY
};
}
CalculateArc(center, beginPoint, cmdPoint, state, out angleF, out sweep, out rect);
if (sweep == 0)
sweep = state.Interpolation == InterpolationMode.ClockwiseCircular ? 360.0f : -360.0f;
if (state.IsInsideRegion)
{
state.CurrentRegion.AddArc(rect, angleF, sweep);
}
else
{
using (var pen = CreatePenForCurrentAperture(state))
{
state.GraphObject.DrawArc(pen, rect, angleF, sweep);
}
}
}
state.CurrentX = origPtX;
state.CurrentY = origPtY;
}
private static double CalculateAngle(CoordinatePair center, CoordinatePair p1, CoordinatePair p2)
{
var vp1 = p1 - center;
var vp2 = p2 - center;
var rad = CoordLength(vp1);
if (Math.Abs(rad - CoordLength(vp2)) > 0.01)
{
//invalid arc
return 0.0;
}
double radius, angle1, angle2;
CalculateAngle(center, p1, p2, out radius, out angle1, out angle2);
/*var angle1 = Math.Asin((double)vp1.Y / rad);
if (angle1 == 0.0 && vp1.X < 0)
angle1 = Math.PI;
var angle2 = Math.Asin((double)vp2.Y / rad);
if (angle2 == 0.0 && vp2.X < 0)
angle2 = Math.PI;*/
return angle1 - angle2;
}
private static double CoordLength(CoordinatePair c)
{
return Math.Sqrt((double)(c.X * c.X) + (double)(c.Y * c.Y));
}
private static double Saturate(double val, double min, double max)
{
return val < min ? min : (val > max ? max : val);
}
private static double CalculateAngle(CoordinatePair vec)
{
var x = (double)vec.X;
var y = (double)vec.Y;
/*if (x > 0)
{
if (y >= 0)
return Math.Atan(y / x);
else
return Math.Atan(y / x) + Math.PI * 2;
}
else if (x == 0.0)
{
if (y > 0)
return Math.PI / 2;
else if (y == 0)
return Math.PI * 2;
else
return 3 * Math.PI / 2;
}
else
{
return Math.Atan(y / x) + Math.PI;
}*/
var res = Math.Atan2(y, x);
if (res < 0)
res += Math.PI * 2;
return res;
}
private static void CalculateAngle(CoordinatePair center, CoordinatePair p1, CoordinatePair p2, out double radius, out double angle1, out double angle2)
{
var vp1 = p1 - center;
var vp2 = p2 - center;
radius = Math.Sqrt((double)(vp1.X * vp1.X) + (double)(vp1.Y * vp1.Y));
var rad2 = Math.Sqrt((double)(vp2.X * vp2.X) + (double)(vp2.Y * vp2.Y));
radius = Math.Max(radius, rad2);
/*var sin1 = Saturate((double)vp1.Y / radius, -1.0, 1.0);
var cos1 = Saturate((double)vp1.X / radius, -1.0, 1.0);
var asin1 = Math.Asin(sin1);
var acos1 = Math.Acos(cos1);
angle1 = asin1;
if (angle1 <= 0)
angle1 = acos1;*/
angle1 = CalculateAngle(vp1);
angle1 = Math.PI * 2 - angle1;
/*var sin2 = Saturate((double)vp2.Y / radius, -1.0, 1.0);
var cos2 = Saturate((double)vp2.X / radius, -1.0, 1.0);
var asin2 = Math.Asin(sin2);
var acos2 = Math.Acos(cos2);
angle2 = asin2;
if (angle2 <= 0)
angle2 = acos2;*/
angle2 = CalculateAngle(vp2);
angle2 = Math.PI * 2 - angle2;
/*angle1 = Math.Asin((double)vp1.Y / radius);
if (vp1.X < 0)
angle1 = Math.PI - angle1;
if (angle1 < 0)
angle1 += 2 * Math.PI;
angle2 = Math.Asin((double)vp2.Y / radius);
if (vp2.X < 0)
angle2 = Math.PI - angle2;
if (angle2 < 0)
angle2 += 2 * Math.PI;*/
var a1 = angle1 * 180.0 / Math.PI;
var a2 = angle2 * 180.0 / Math.PI;
Debug.WriteLine($"vp1({vp1.X},{vp1.Y}), angle = {a1}");
Debug.WriteLine($"vp2({vp2.X},{vp2.Y}), angle = {a2}");
}
private static void CalculateArc(CoordinatePair center, CoordinatePair p1, CoordinatePair p2, GraphicsState state,
out float angle, out float sweep, out Rectangle rect)
{
double radius, angle1, angle2;
CalculateAngle(center, p1, p2, out radius, out angle1, out angle2);
/*if (angle2 == 0.0 && state.Interpolation == InterpolationMode.ClockwiseCircular)
angle2 = Math.PI * 2;
if (angle1 == 0.0 && state.Interpolation == InterpolationMode.CounterclockwiseCircular)
angle1 = Math.PI * 2;*/
if (state.Interpolation == InterpolationMode.ClockwiseCircular && angle2 < angle1)
angle2 += Math.PI * 2;
else if (state.Interpolation == InterpolationMode.CounterclockwiseCircular && angle2 > angle1)
angle2 -= Math.PI * 2;
angle2 = angle2 - angle1;
if ((state.Interpolation == InterpolationMode.ClockwiseCircular && angle2 < 0) ||
(state.Interpolation == InterpolationMode.CounterclockwiseCircular && angle2 > 0))
{
//angle2 = -(2 * Math.PI - angle2);
1.ToString();
}
/*if (state.Interpolation == InterpolationMode.ClockwiseCircular && state.IsMultiQuadrant)
angle2 = (2 * Math.PI - angle2);*/
var a1 = angle1 * 180.0 / Math.PI;
var a2 = angle2 * 180.0 / Math.PI;
Debug.WriteLine($"start {a1} sweep {a2} int mode {state.Interpolation}");
var lowPt = state.CalcCoords(center.X - (decimal)radius, center.Y + (decimal)radius);
var hiPt = state.CalcCoords(center.X + (decimal)radius, center.Y - (decimal)radius);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
angle = (float)(angle1 * (180.0 / Math.PI));
sweep = (float)(angle2 * (180.0 / Math.PI));
Debug.WriteLine($"angle {angle}, sweep {sweep}");
}
private void ProcessCommand(OperationMoveCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
var origPtX = cmd.HasX ? cmd.X : state.CurrentX;
var origPtY = cmd.HasY ? cmd.Y : state.CurrentY;
var pt = state.CalcCoords(origPtX, origPtY);
if (state.IsInsideRegion)
{
DrawRegion(state);
//state.CurrentRegion.Add(pt);
}
else
{
if (cmd.HasX)
state.CurrentX = cmd.X;
if (cmd.HasY)
state.CurrentY = cmd.Y;
}
state.CurrentX = origPtX;
state.CurrentY = origPtY;
}
private void ProcessCommand(OperationFlashCommand cmd, GraphicsState state)
{
if (cmd == null)
return;
var origPtX = cmd.HasX ? cmd.X : state.CurrentX;
var origPtY = cmd.HasY ? cmd.Y : state.CurrentY;
DrawCurrentAperture(state, origPtX, origPtY);
state.CurrentX = origPtX;
state.CurrentY = origPtY;
}
private void DrawCurrentAperture(GraphicsState state, decimal x, decimal y)
{
var currAp = state.Apertures[state.CurrentApertureNumber];
if (currAp.Template == "C")
{
var halfD = currAp.Diameter * state.Divisor / 2;
var lowPt = state.CalcCoords(x - halfD, y + halfD);
var hiPt = state.CalcCoords(x + halfD, y - halfD);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
var rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
using (var pen = new Pen(GetBrushColor(state.IsDarkPolarity)))
{
state.GraphObject.DrawEllipse(pen, rect);
}
state.GraphObject.FillEllipse(GetBrushColor(state.IsDarkPolarity), rect);
}
else if (currAp.Template == "R")
{
var halfX = currAp.SizeX * state.Divisor / 2;
var halfY = currAp.SizeY * state.Divisor / 2;
var lowPt = state.CalcCoords(x - halfX, y + halfY);
var hiPt = state.CalcCoords(x + halfX, y - halfY);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
var rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
using (var pen = new Pen(GetBrushColor(state.IsDarkPolarity)))
{
state.GraphObject.DrawRectangle(pen, rect);
}
state.GraphObject.FillRectangle(GetBrushColor(state.IsDarkPolarity), rect);
}
else if (currAp.Template == "P")
{
//state.GraphObject.Fi
var points = new Point[currAp.VerticesCount];
for (int i = 0; i < currAp.VerticesCount; i++)
{
var angle = i * Math.PI * 2 / currAp.VerticesCount;
var currX = x + (decimal)Math.Cos(angle) * currAp.Diameter / 2 * state.Divisor;
var currY = y + (decimal)Math.Sin(angle) * currAp.Diameter / 2 * state.Divisor;
points[i] = state.CalcCoords(currX, currY);
}
using (var pen = new Pen(GetBrushColor(state.IsDarkPolarity)))
{
state.GraphObject.DrawPolygon(pen, points);
}
state.GraphObject.FillPolygon(GetBrushColor(state.IsDarkPolarity), points);
}
else if (currAp.Template == "O")
{
if (currAp.SizeX == currAp.SizeY)
{
var halfX = currAp.SizeX * state.Divisor / 2;
var halfY = currAp.SizeY * state.Divisor / 2;
var lowPt = state.CalcCoords(x - halfX, y + halfY);
var hiPt = state.CalcCoords(x + halfX, y - halfY);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
var rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
using (var pen = new Pen(GetBrushColor(state.IsDarkPolarity)))
{
state.GraphObject.DrawRectangle(pen, rect);
}
state.GraphObject.FillRectangle(GetBrushColor(state.IsDarkPolarity), rect);
}
else
{
var isRectX = currAp.SizeX > currAp.SizeY;
var circleRadius = Math.Min(currAp.SizeX, currAp.SizeY) * state.Divisor / 2;
var circleOffset = Math.Abs(currAp.SizeY - currAp.SizeX) * state.Divisor / 2;
var circleOffsetX = isRectX ? circleOffset : 0.0m;
var circleOffsetY = isRectX ? 0.0m : circleOffset;
var c1Low = state.CalcCoords(x - circleOffsetX - circleRadius, y - circleOffsetY + circleRadius);
var c1Hi = state.CalcCoords(x - circleOffsetX + circleRadius, y - circleOffsetY - circleRadius);
var c1Rect = new Rectangle(c1Low.X, c1Low.Y, c1Hi.X - c1Low.X, Math.Abs(c1Hi.Y - c1Low.Y));
var c2Low = state.CalcCoords(x + circleOffsetX - circleRadius, y + circleOffsetY + circleRadius);
var c2Hi = state.CalcCoords(x + circleOffsetX + circleRadius, y + circleOffsetY - circleRadius);
var c2Rect = new Rectangle(c2Low.X, c2Low.Y, c2Hi.X - c2Low.X, Math.Abs(c2Hi.Y - c2Low.Y));
var connLow = state.CalcCoords(x - circleOffsetX - (isRectX ? 0.0m : circleRadius), y + circleOffsetY + (isRectX ? circleRadius : 0.0m));
var connHi = state.CalcCoords(x + circleOffsetX + (isRectX ? 0.0m : circleRadius), y - circleOffsetY - (isRectX ? circleRadius : 0.0m));
var connRect = new Rectangle(connLow.X, connLow.Y, connHi.X - connLow.X, Math.Abs(connHi.Y - connLow.Y));
using (var pen = new Pen(GetBrushColor(state.IsDarkPolarity)))
{
state.GraphObject.DrawEllipse(pen, c1Rect);
state.GraphObject.DrawEllipse(pen, c2Rect);
state.GraphObject.DrawRectangle(pen, connRect);
}
state.GraphObject.FillEllipse(GetBrushColor(state.IsDarkPolarity), c1Rect);
state.GraphObject.FillEllipse(GetBrushColor(state.IsDarkPolarity), c2Rect);
state.GraphObject.FillRectangle(GetBrushColor(state.IsDarkPolarity), connRect);
}
}
else if (currAp.Template == "M")
{
var macro = state.ApertureMacros[currAp.MacroName];
RenderMacro(macro, state, x, y);
}
}
private void RenderMacro(ApertureMacroDefinitionCommand cmd, GraphicsState state, decimal x, decimal y)
{
foreach (var primitive in cmd.Primitives)
{
switch (primitive.Id)
{
case CircleMacroPrimitive.CODE:
RenderCircleMacro((CircleMacroPrimitive)primitive, state, x, y);
break;
case MoireMacroPrimitive.CODE:
RenderMoireMacro((MoireMacroPrimitive) primitive, state, x, y);
break;
case ThermalMacroPrimitive.CODE:
RenderThermalMacro((ThermalMacroPrimitive) primitive, state, x, y);
break;
case OutlineMacroPrimitive.CODE:
RenderOutlineMacro((OutlineMacroPrimitive) primitive, state, x, y);
break;
case CenterLineMacroPrimitive.CODE:
RenderCenterLineMarco((CenterLineMacroPrimitive) primitive, state, x, y);
break;
default:
Console.WriteLine($"ERROR - invalid primitive ID {primitive.Id}");
break;
}
}
}
private void RenderCircleMacro(CircleMacroPrimitive macro, GraphicsState state, decimal x, decimal y)
{
var center = new CoordinatePair
{
X = x + macro.Center.X * state.Divisor,
Y = y + macro.Center.Y * state.Divisor
};
var diameter = state.CalcRelativeCoord(macro.Diameter * state.Divisor);
var centerDraw = state.CalcCoords(center.X, center.Y);
var rect = new Rectangle(-diameter / 2, -diameter / 2, diameter, diameter);
var mat = state.GraphObject.Transform;
state.GraphObject.TranslateTransform(centerDraw.X, centerDraw.Y);
state.GraphObject.RotateTransform((float)macro.Rotation);
state.GraphObject.FillEllipse(GetBrushColor(state.IsDarkPolarity), rect);
state.GraphObject.Transform = mat;
}
private void RenderCenterLineMarco(CenterLineMacroPrimitive macro, GraphicsState state, decimal x, decimal y)
{
var center = new CoordinatePair
{
X = x + macro.Center.X * state.Divisor,
Y = y + macro.Center.Y * state.Divisor
};
var sizeX = state.CalcRelativeCoord(macro.Width * state.Divisor);
var sizeY = state.CalcRelativeCoord(macro.Height * state.Divisor);
var centerDraw = state.CalcCoords(center.X, center.Y);
var rect = new Rectangle(-sizeX/2, -sizeY/2, sizeX, sizeY);
var mat = state.GraphObject.Transform;
state.GraphObject.TranslateTransform(centerDraw.X, centerDraw.Y);
state.GraphObject.RotateTransform((float) macro.Rotation);
state.GraphObject.FillRectangle(GetBrushColor(state.IsDarkPolarity), rect);
state.GraphObject.Transform = mat;
}
private void RenderMoireMacro(MoireMacroPrimitive macro, GraphicsState state, decimal x, decimal y)
{
var center = new CoordinatePair
{
X = x + macro.Center.X * state.Divisor,
Y = y + macro.Center.Y * state.Divisor
};
using (var penCircle = new Pen(GetBrushColor(true), (float)state.ScaleByRenderScale(macro.RingThickness)))
{
//state.GraphObject.drawE
for (int i = 0; i < macro.MaxNumberOfRings; i++)
{
var size = macro.OuterRingDiameter / 2 - macro.RingThickness / 2 - (macro.RingThickness + macro.GapBetweenRings) * i;
if (size < 0)
break;
size *= state.Divisor;
var lowPt = state.CalcCoords(center.X - size, center.Y + size);
var hiPt = state.CalcCoords(center.X + size, center.Y - size);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
var rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
state.GraphObject.DrawEllipse(penCircle, rect);
}
}
using (var penCross = new Pen(GetBrushColor(true), (float) state.ScaleByRenderScale(macro.CrosshairThickness)))
{
var size = macro.CrosshairLength / 2;
size *= state.Divisor;
var lowPt = state.CalcCoords(center.X - size, center.Y);
var hiPt = state.CalcCoords(center.X + size, center.Y);
state.GraphObject.DrawLine(penCross, lowPt, hiPt);
lowPt = state.CalcCoords(center.X, center.Y + size);
hiPt = state.CalcCoords(center.X, center.Y - size);
state.GraphObject.DrawLine(penCross, lowPt, hiPt);
}
}
private void RenderThermalMacro(ThermalMacroPrimitive macro, GraphicsState state, decimal x, decimal y)
{
var center = new CoordinatePair
{
X = x + macro.Center.X * state.Divisor,
Y = y + macro.Center.Y * state.Divisor
};
var thickness = macro.OuterDiameter / 2 - macro.InnerDiameter / 2;
var size = macro.InnerDiameter / 2 + thickness / 2;
size *= state.Divisor;
using (var penCircle = new Pen(GetBrushColor(true), (float) state.ScaleByRenderScale(thickness)))
{
var lowPt = state.CalcCoords(center.X - size, center.Y + size);
var hiPt = state.CalcCoords(center.X + size, center.Y - size);
if (lowPt.X == hiPt.X)
hiPt.X++;
if (lowPt.Y == hiPt.Y)
hiPt.Y++;
var rect = new Rectangle(lowPt.X, lowPt.Y, hiPt.X - lowPt.X, Math.Abs(hiPt.Y - lowPt.Y));
state.GraphObject.DrawEllipse(penCircle, rect);
}
size = macro.OuterDiameter / 2 + thickness / 2;
size *= state.Divisor;
using (var penGap = new Pen(GetBrushColor(false), (float) state.ScaleByRenderScale(macro.GapThickness)))
{
var mat = new Matrix();
var centerPt = state.CalcCoords(center.X, center.Y);
mat.RotateAt((float) macro.Rotation, centerPt);
var lowPt = state.CalcCoords(center.X - size, center.Y);
var hiPt = state.CalcCoords(center.X + size, center.Y);
var points = new[] {lowPt, hiPt};
mat.TransformPoints(points);
state.GraphObject.DrawLine(penGap, points[0], points[1]);
lowPt = state.CalcCoords(center.X, center.Y + size);
hiPt = state.CalcCoords(center.X, center.Y - size);
points = new[] { lowPt, hiPt };
mat.TransformPoints(points);
state.GraphObject.DrawLine(penGap, points[0], points[1]);
}
}
private void RenderOutlineMacro(OutlineMacroPrimitive macro, GraphicsState state, decimal x, decimal y)
{
var points = new List<Point>();
foreach (var pt in macro.Points)
{
points.Add(state.CalcCoords(x + pt.X * state.Divisor, y + pt.Y * state.Divisor));
}
state.GraphObject.FillPolygon(GetBrushColor(true), points.ToArray());
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_activeBrush.Dispose();
_inactiveBrush.Dispose();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private sealed class GraphicsState
{
private readonly decimal _renderScale;
private readonly decimal _renderBorder;
private readonly decimal _renderOffsetX;
private readonly decimal _renderOffsetY;
public GraphicsState(decimal renderScale, decimal renderBorder, decimal renderOffsetX, decimal renderOffsetY)
{
_renderScale = renderScale;
_renderBorder = renderBorder;
_renderOffsetX = renderOffsetX;
_renderOffsetY = renderOffsetY;
CurrentScale = 1;
IsDarkPolarity = true;
}
public Point CalcCoords(decimal x, decimal y)
{
var finalX = (int)Math.Round(((x / Divisor) + _renderOffsetX + _renderBorder) * _renderScale);
var finalY = (int)Math.Round(((y / Divisor) + _renderOffsetY + _renderBorder) * _renderScale);
finalY = (int)GraphObject.VisibleClipBounds.Size.Height - finalY;
return new Point(finalX, finalY);
}
public Point CalcCoordsForCurrentPoint()
{
return CalcCoords(CurrentX, CurrentY);
}
public CoordinatePair GetCurrentPoint()
{
return new CoordinatePair
{
X = CurrentX,
Y = CurrentY
};
}
public int CalcRelativeCoord(decimal x)
{
return (int)Math.Round((x / Divisor) * _renderScale);
}
public decimal ScaleByRenderScale(decimal x)
{
return x * _renderScale;
}
public float CalcRelativeCoordFloat(decimal x)
{
return (float)Math.Round((x / Divisor) * _renderScale);
}
public int IntPrecision { get; set; }
public int DecPrecision { get; set; }
public decimal Divisor { get; set; }
public decimal CurrentX { get; set; }
public decimal CurrentY { get; set; }
public int CurrentApertureNumber { get; set; }
public InterpolationMode Interpolation { get; set; }
public bool IsMultiQuadrant { get; set; }
public bool IsDarkPolarity { get; set; }
public bool IsMirrorX { get; set; }
public bool IsMirrorY { get; set; }
public decimal CurrentRotation { get; set; }
public decimal CurrentScale { get; set; }
public bool IsInsideRegion { get; set; }
public IDictionary<int, ApertureDefinitionCommand> Apertures { get; private set; } = new Dictionary<int, ApertureDefinitionCommand>();
public IDictionary<string, ApertureMacroDefinitionCommand> ApertureMacros { get; private set; } = new Dictionary<string, ApertureMacroDefinitionCommand>();
public Graphics GraphObject { get; set; }
public GraphicsPath CurrentRegion { get; private set; } = new GraphicsPath();
}
private enum InterpolationMode
{
Linear,
ClockwiseCircular,
CounterclockwiseCircular
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SmartDate.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Provides a date data type that understands the concept</summary>
//-----------------------------------------------------------------------
using System;
using Csla.Properties;
using Csla.Serialization.Mobile;
namespace Csla
{
/// <summary>
/// Provides a date data type that understands the concept
/// of an empty date value.
/// </summary>
/// <remarks>
/// See Chapter 5 for a full discussion of the need for this
/// data type and the design choices behind it.
/// </remarks>
[Serializable()]
#if !NETFX_CORE
[System.ComponentModel.TypeConverter(typeof(Csla.Core.TypeConverters.SmartDateConverter))]
#endif
public struct SmartDate : Csla.Core.ISmartField,
#if !NETFX_CORE
IConvertible,
#endif
IComparable, IFormattable, IMobileObject
{
private DateTime _date;
private bool _initialized;
private EmptyValue _emptyValue;
private string _format;
private static string _defaultFormat;
#if !NETFX_CORE
[NonSerialized]
#endif
[NotUndoable]
private static Func<string, DateTime?> _customParser;
#region EmptyValue enum
/// <summary>
/// Indicates the empty value of a
/// SmartDate.
/// </summary>
public enum EmptyValue
{
/// <summary>
/// Indicates that an empty SmartDate
/// is the smallest date.
/// </summary>
MinDate,
/// <summary>
/// Indicates that an empty SmartDate
/// is the largest date.
/// </summary>
MaxDate
}
#endregion
#region Constructors
static SmartDate()
{
_defaultFormat = "d";
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
// provide a dummy value to allow real initialization
_date = DateTime.MinValue;
SetEmptyDate(_emptyValue);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
// provide a dummy value to allow real initialization
_date = DateTime.MinValue;
SetEmptyDate(_emptyValue);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTime value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <param name="kind">One of the DateTimeKind values.</param>
public SmartDate(DateTime value, EmptyValue emptyValue, DateTimeKind kind)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = DateTime.SpecifyKind(value, kind);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTime? value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime? value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime? value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// <para>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </para><para>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </para>
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTimeOffset value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public SmartDate(DateTimeOffset value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public SmartDate(DateTimeOffset value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object (as text).</param>
public SmartDate(string value)
{
_emptyValue = EmptyValue.MinDate;
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object (as text).</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(string value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object (as text).</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(string value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
private static EmptyValue GetEmptyValue(bool emptyIsMin)
{
if (emptyIsMin)
return EmptyValue.MinDate;
else
return EmptyValue.MaxDate;
}
private void SetEmptyDate(EmptyValue emptyValue)
{
if (emptyValue == SmartDate.EmptyValue.MinDate)
this.Date = DateTime.MinValue;
else
this.Date = DateTime.MaxValue;
}
#endregion
#region Text Support
/// <summary>
/// Sets the global default format string used by all new
/// SmartDate values going forward.
/// </summary>
/// <remarks>
/// The default global format string is "d" unless this
/// method is called to change that value. Existing SmartDate
/// values are unaffected by this method, only SmartDate
/// values created after calling this method are affected.
/// </remarks>
/// <param name="formatString">
/// The format string should follow the requirements for the
/// .NET System.String.Format statement.
/// </param>
public static void SetDefaultFormatString(string formatString)
{
_defaultFormat = formatString;
}
/// <summary>
/// Gets or sets the format string used to format a date
/// value when it is returned as text.
/// </summary>
/// <remarks>
/// The format string should follow the requirements for the
/// .NET System.String.Format statement.
/// </remarks>
/// <value>A format string.</value>
public string FormatString
{
get
{
if (_format == null)
_format = _defaultFormat;
return _format;
}
set
{
_format = value;
}
}
/// <summary>
/// Gets or sets the date value.
/// </summary>
/// <remarks>
/// <para>
/// This property can be used to set the date value by passing a
/// text representation of the date. Any text date representation
/// that can be parsed by the .NET runtime is valid.
/// </para><para>
/// When the date value is retrieved via this property, the text
/// is formatted by using the format specified by the
/// <see cref="FormatString" /> property. The default is the
/// short date format (d).
/// </para>
/// </remarks>
public string Text
{
get { return DateToString(this.Date, FormatString, _emptyValue); }
set { this.Date = StringToDate(value, _emptyValue); }
}
#endregion
#region Date Support
/// <summary>
/// Gets or sets the date value.
/// </summary>
public DateTime Date
{
get
{
if (!_initialized)
{
_date = _emptyValue == SmartDate.EmptyValue.MinDate ? DateTime.MinValue : DateTime.MaxValue;
_initialized = true;
}
return _date;
}
set
{
_date = value;
_initialized = true;
}
}
/// <summary>
/// Gets the value as a DateTimeOffset.
/// </summary>
public DateTimeOffset ToDateTimeOffset()
{
return new DateTimeOffset(this.Date);
}
/// <summary>
/// Gets the value as a DateTime?.
/// </summary>
public DateTime? ToNullableDate()
{
if (this.IsEmpty)
return new DateTime?();
else
return new DateTime?(this.Date);
}
#endregion
#region System.Object overrides
/// <summary>
/// Returns a text representation of the date value.
/// </summary>
public override string ToString()
{
return this.Text;
}
/// <summary>
/// Returns a text representation of the date value.
/// </summary>
/// <param name="format">
/// A standard .NET format string.
/// </param>
public string ToString(string format)
{
if (string.IsNullOrEmpty(format))
return this.ToString();
else
return DateToString(this.Date, format, _emptyValue);
}
/// <summary>
/// Compares this object to another <see cref="SmartDate"/>
/// for equality.
/// </summary>
/// <param name="obj">Object to compare for equality.</param>
public override bool Equals(object obj)
{
if (obj is SmartDate)
{
SmartDate tmp = (SmartDate)obj;
if (this.IsEmpty && tmp.IsEmpty)
return true;
else
return this.Date.Equals(tmp.Date);
}
else if (obj is DateTime)
return this.Date.Equals((DateTime)obj);
else if (obj is string)
return (this.CompareTo(obj.ToString()) == 0);
else
return false;
}
/// <summary>
/// Returns a hash code for this object.
/// </summary>
public override int GetHashCode()
{
return this.Date.GetHashCode();
}
#endregion
#region DBValue
#if !NETFX_CORE
/// <summary>
/// Gets a database-friendly version of the date value.
/// </summary>
/// <remarks>
/// <para>
/// If the SmartDate contains an empty date, this returns <see cref="DBNull"/>.
/// Otherwise the actual date value is returned as type Date.
/// </para><para>
/// This property is very useful when setting parameter values for
/// a Command object, since it automatically stores null values into
/// the database for empty date values.
/// </para><para>
/// When you also use the SafeDataReader and its GetSmartDate method,
/// you can easily read a null value from the database back into a
/// SmartDate object so it remains considered as an empty date value.
/// </para>
/// </remarks>
public object DBValue
{
get
{
if (this.IsEmpty)
return DBNull.Value;
else
return this.Date;
}
}
#endif
#endregion
#region Empty Dates
/// <summary>
/// Gets a value indicating whether this object contains an empty date.
/// </summary>
public bool IsEmpty
{
get
{
if (_emptyValue == EmptyValue.MinDate)
return this.Date.Equals(DateTime.MinValue);
else
return this.Date.Equals(DateTime.MaxValue);
}
}
/// <summary>
/// Gets a value indicating whether an empty date is the
/// min or max possible date value.
/// </summary>
/// <remarks>
/// Whether an empty date is considered to be the smallest or largest possible
/// date is only important for comparison operations. This allows you to
/// compare an empty date with a real date and get a meaningful result.
/// </remarks>
public bool EmptyIsMin
{
get { return (_emptyValue == EmptyValue.MinDate); }
}
#endregion
#region Conversion Functions
/// <summary>
/// Gets or sets the custom parser.
///
/// The CustomParser is called first in TryStringToDate to allow custom parsing.
/// The parser method must return null if unable to parse and allow SmartDate to try default parsing.
/// </summary>
/// <value>
/// The custom parser.
/// </value>
public static Func<string, DateTime?> CustomParser
{
get { return _customParser; }
set { _customParser = value; }
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
/// <remarks>
/// EmptyIsMin will default to true.
/// </remarks>
public static SmartDate Parse(string value)
{
return new SmartDate(value);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
public static SmartDate Parse(string value, EmptyValue emptyValue)
{
return new SmartDate(value, emptyValue);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
public static SmartDate Parse(string value, bool emptyIsMin)
{
return new SmartDate(value, emptyIsMin);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="result">The resulting SmartDate value if the parse was successful.</param>
/// <returns>A value indicating if the parse was successful.</returns>
public static bool TryParse(string value, ref SmartDate result)
{
return TryParse(value, EmptyValue.MinDate, ref result);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <param name="result">The resulting SmartDate value if the parse was successful.</param>
/// <returns>A value indicating if the parse was successful.</returns>
public static bool TryParse(string value, EmptyValue emptyValue, ref SmartDate result)
{
System.DateTime dateResult = DateTime.MinValue;
if (TryStringToDate(value, emptyValue, ref dateResult))
{
result = new SmartDate(dateResult, emptyValue);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue of the Date datatype.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value)
{
return StringToDate(value, true);
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue or MaxValue of the Date datatype depending
/// on the EmptyIsMin parameter.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value, bool emptyIsMin)
{
return StringToDate(value, GetEmptyValue(emptyIsMin));
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue or MaxValue of the Date datatype depending
/// on the EmptyIsMin parameter.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value, EmptyValue emptyValue)
{
DateTime result = DateTime.MinValue;
if (TryStringToDate(value, emptyValue, ref result))
return result;
else
throw new ArgumentException(Resources.StringToDateException);
}
private static bool TryStringToDate(string value, EmptyValue emptyValue, ref DateTime result)
{
DateTime tmp;
// call custom parser if set...
if (_customParser != null)
{
var tmpValue = _customParser.Invoke(value);
// i f custom parser returned a value then parsing succeeded
if (tmpValue.HasValue)
{
result = tmpValue.Value;
return true;
}
}
if (String.IsNullOrEmpty(value))
{
result = emptyValue == EmptyValue.MinDate ? DateTime.MinValue : DateTime.MaxValue;
return true;
}
if (DateTime.TryParse(value, out tmp))
{
result = tmp;
return true;
}
string ldate = value.Trim().ToLower();
if (ldate == Resources.SmartDateT ||
ldate == Resources.SmartDateToday ||
ldate == ".")
{
result = DateTime.Now;
return true;
}
if (ldate == Resources.SmartDateY ||
ldate == Resources.SmartDateYesterday ||
ldate == "-")
{
result = DateTime.Now.AddDays(-1);
return true;
}
if (ldate == Resources.SmartDateTom ||
ldate == Resources.SmartDateTomorrow ||
ldate == "+")
{
result = DateTime.Now.AddDays(1);
return true;
}
return false;
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// The date is considered empty if it matches the min value for
/// the Date datatype. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString)
{
return DateToString(value, formatString, true);
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// Whether the date value is considered empty is determined by
/// the EmptyIsMin parameter value. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString, bool emptyIsMin)
{
return DateToString(value, formatString, GetEmptyValue(emptyIsMin));
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// Whether the date value is considered empty is determined by
/// the EmptyIsMin parameter value. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString, EmptyValue emptyValue)
{
if (emptyValue == EmptyValue.MinDate)
{
if (value == DateTime.MinValue)
return string.Empty;
}
else
{
if (value == DateTime.MaxValue)
return string.Empty;
}
return string.Format("{0:" + formatString + "}", value);
}
#endregion
#region Manipulation Functions
/// <summary>
/// Compares one SmartDate to another.
/// </summary>
/// <remarks>
/// This method works the same as the DateTime.CompareTo method
/// on the Date datetype, with the exception that it
/// understands the concept of empty date values.
/// </remarks>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(SmartDate value)
{
if (this.IsEmpty && value.IsEmpty)
return 0;
else
return _date.CompareTo(value.Date);
}
/// <summary>
/// Compares one SmartDate to another.
/// </summary>
/// <remarks>
/// This method works the same as the DateTime.CompareTo method
/// on the Date datetype, with the exception that it
/// understands the concept of empty date values.
/// </remarks>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
int IComparable.CompareTo(object value)
{
if (value is SmartDate)
return CompareTo((SmartDate)value);
else
throw new ArgumentException(Resources.ValueNotSmartDateException);
}
/// <summary>
/// Compares a SmartDate to a text date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(string value)
{
return this.Date.CompareTo(StringToDate(value, _emptyValue));
}
/// <summary>
/// Compares a SmartDate to a date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime for this comparison. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public int CompareTo(DateTimeOffset value)
{
return this.Date.CompareTo(value.DateTime);
}
/// <summary>
/// Compares a SmartDate to a date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(DateTime value)
{
return this.Date.CompareTo(value);
}
/// <summary>
/// Adds a TimeSpan onto the object.
/// </summary>
/// <param name="value">Span to add to the date.</param>
public DateTime Add(TimeSpan value)
{
if (IsEmpty)
return this.Date;
else
return this.Date.Add(value);
}
/// <summary>
/// Subtracts a TimeSpan from the object.
/// </summary>
/// <param name="value">Span to subtract from the date.</param>
public DateTime Subtract(TimeSpan value)
{
if (IsEmpty)
return this.Date;
else
return this.Date.Subtract(value);
}
/// <summary>
/// Subtracts a DateTimeOffset from the object.
/// </summary>
/// <param name="value">DateTimeOffset to subtract from the date.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime for this comparison. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public TimeSpan Subtract(DateTimeOffset value)
{
if (IsEmpty)
return TimeSpan.Zero;
else
return this.Date.Subtract(value.DateTime);
}
/// <summary>
/// Subtracts a DateTime from the object.
/// </summary>
/// <param name="value">Date to subtract from the date.</param>
public TimeSpan Subtract(DateTime value)
{
if (IsEmpty)
return TimeSpan.Zero;
else
return this.Date.Subtract(value);
}
#endregion
#region Operators
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, SmartDate obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, SmartDate obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Convert a SmartDate to a String.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator string(SmartDate obj1)
{
return obj1.Text;
}
/// <summary>
/// Convert a SmartDate to a DateTime.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator System.DateTime(SmartDate obj1)
{
return obj1.Date;
}
/// <summary>
/// Convert a SmartDate to a nullable DateTime.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator System.DateTime?(SmartDate obj1)
{
return obj1.ToNullableDate();
}
/// <summary>
/// Convert a SmartDate to a DateTimeOffset.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator DateTimeOffset(SmartDate obj1)
{
return obj1.ToDateTimeOffset();
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static explicit operator SmartDate(string dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static implicit operator SmartDate(System.DateTime dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static implicit operator SmartDate(System.DateTime? dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static explicit operator SmartDate(DateTimeOffset dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, DateTime obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, DateTime obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, string obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, string obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Addition operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="span">Span to add</param>
/// <returns></returns>
public static SmartDate operator +(SmartDate start, TimeSpan span)
{
return new SmartDate(start.Add(span), start.EmptyIsMin);
}
/// <summary>
/// Subtraction operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="span">Span to subtract</param>
/// <returns></returns>
public static SmartDate operator -(SmartDate start, TimeSpan span)
{
return new SmartDate(start.Subtract(span), start.EmptyIsMin);
}
/// <summary>
/// Subtraction operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="finish">Second date/time</param>
/// <returns></returns>
public static TimeSpan operator -(SmartDate start, SmartDate finish)
{
return start.Subtract(finish.Date);
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
#endregion
#if !NETFX_CORE
#region IConvertible
System.TypeCode IConvertible.GetTypeCode()
{
return ((IConvertible)_date).GetTypeCode();
}
bool IConvertible.ToBoolean(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToBoolean(provider);
}
byte IConvertible.ToByte(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToByte(provider);
}
char IConvertible.ToChar(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToChar(provider);
}
System.DateTime IConvertible.ToDateTime(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDateTime(provider);
}
decimal IConvertible.ToDecimal(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDecimal(provider);
}
double IConvertible.ToDouble(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDouble(provider);
}
short IConvertible.ToInt16(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt16(provider);
}
int IConvertible.ToInt32(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt32(provider);
}
long IConvertible.ToInt64(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt64(provider);
}
sbyte IConvertible.ToSByte(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToSByte(provider);
}
float IConvertible.ToSingle(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToSingle(provider);
}
string IConvertible.ToString(System.IFormatProvider provider)
{
return ((IConvertible)Text).ToString(provider);
}
object IConvertible.ToType(System.Type conversionType, System.IFormatProvider provider)
{
if (conversionType.Equals(typeof(string)))
return ((IConvertible)Text).ToType(conversionType, provider);
else if (conversionType.Equals(typeof(SmartDate)))
return this;
else
return ((IConvertible)_date).ToType(conversionType, provider);
}
ushort IConvertible.ToUInt16(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt16(provider);
}
uint IConvertible.ToUInt32(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt32(provider);
}
ulong IConvertible.ToUInt64(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt64(provider);
}
#endregion
#endif
#region IFormattable Members
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return this.ToString(format);
}
#endregion
#region IMobileObject Members
void IMobileObject.GetState(SerializationInfo info)
{
info.AddValue("SmartDate._date", _date);
info.AddValue("SmartDate._defaultFormat", _defaultFormat);
info.AddValue("SmartDate._emptyValue", _emptyValue.ToString());
info.AddValue("SmartDate._initialized", _initialized);
info.AddValue("SmartDate._format", _format);
}
void IMobileObject.SetState(SerializationInfo info)
{
_date = info.GetValue<DateTime>("SmartDate._date");
_defaultFormat = info.GetValue<string>("SmartDate._defaultFormat");
_emptyValue = (EmptyValue)System.Enum.Parse(typeof(EmptyValue), info.GetValue<string>("SmartDate._emptyValue"), true);
_format = info.GetValue<string>("SmartDate._format");
_initialized = info.GetValue<bool>("SmartDate._initialized");
}
void IMobileObject.SetChildren(SerializationInfo info, MobileFormatter formatter)
{
//
}
void IMobileObject.GetChildren(SerializationInfo info, MobileFormatter formatter)
{
//
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>AdGroupFeed</c> resource.</summary>
public sealed partial class AdGroupFeedName : gax::IResourceName, sys::IEquatable<AdGroupFeedName>
{
/// <summary>The possible contents of <see cref="AdGroupFeedName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </summary>
CustomerAdGroupFeed = 1,
}
private static gax::PathTemplate s_customerAdGroupFeed = new gax::PathTemplate("customers/{customer_id}/adGroupFeeds/{ad_group_id_feed_id}");
/// <summary>Creates a <see cref="AdGroupFeedName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdGroupFeedName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupFeedName"/> with the pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupFeedName"/> constructed from the provided ids.</returns>
public static AdGroupFeedName FromCustomerAdGroupFeed(string customerId, string adGroupId, string feedId) =>
new AdGroupFeedName(ResourceNameType.CustomerAdGroupFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupFeedName"/> with pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupFeedName"/> with pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string feedId) =>
FormatCustomerAdGroupFeed(customerId, adGroupId, feedId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupFeedName"/> with pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupFeedName"/> with pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupFeed(string customerId, string adGroupId, string feedId) =>
s_customerAdGroupFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}");
/// <summary>Parses the given resource name string into a new <see cref="AdGroupFeedName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupFeedName"/> if successful.</returns>
public static AdGroupFeedName Parse(string adGroupFeedName) => Parse(adGroupFeedName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupFeedName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdGroupFeedName"/> if successful.</returns>
public static AdGroupFeedName Parse(string adGroupFeedName, bool allowUnparsed) =>
TryParse(adGroupFeedName, allowUnparsed, out AdGroupFeedName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupFeedName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupFeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupFeedName, out AdGroupFeedName result) =>
TryParse(adGroupFeedName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupFeedName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupFeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupFeedName, bool allowUnparsed, out AdGroupFeedName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupFeedName, nameof(adGroupFeedName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupFeed.TryParseName(adGroupFeedName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupFeed(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupFeedName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string customerId = null, string feedId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CustomerId = customerId;
FeedId = feedId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupFeedName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupFeedName(string customerId, string adGroupId, string feedId) : this(ResourceNameType.CustomerAdGroupFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupFeed: return s_customerAdGroupFeed.Expand(CustomerId, $"{AdGroupId}~{FeedId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdGroupFeedName);
/// <inheritdoc/>
public bool Equals(AdGroupFeedName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupFeedName a, AdGroupFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupFeedName a, AdGroupFeedName b) => !(a == b);
}
public partial class AdGroupFeed
{
/// <summary>
/// <see cref="AdGroupFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupFeedName ResourceNameAsAdGroupFeedName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupFeedName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary>
internal FeedName FeedAsFeedName
{
get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true);
set => Feed = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
}
}
| |
// GtkSharp.Generation.CallbackGen.cs - The Callback Generatable.
//
// Author: Mike Kestner <[email protected]>
//
// Copyright (c) 2002-2003 Mike Kestner
// Copyright (c) 2007 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.IO;
using System.Xml;
public class CallbackGen : GenBase, IAccessor {
private Parameters parms;
private Signature sig = null;
private ReturnValue retval;
private bool valid = true;
public CallbackGen (XmlElement ns, XmlElement elem) : base (ns, elem)
{
retval = new ReturnValue (elem ["return-type"]);
parms = new Parameters (elem ["parameters"]);
parms.HideData = true;
}
public override string DefaultValue {
get { return "null"; }
}
public override bool Validate ()
{
if (!retval.Validate ()) {
Console.WriteLine ("rettype: " + retval.CType + " in callback " + CName);
Statistics.ThrottledCount++;
valid = false;
return false;
}
if (!parms.Validate ()) {
Console.WriteLine (" in callback " + CName);
Statistics.ThrottledCount++;
valid = false;
return false;
}
valid = true;
return true;
}
public string InvokerName {
get {
if (!valid)
return String.Empty;
return NS + "Sharp." + Name + "Invoker";
}
}
public override string MarshalType {
get {
if (valid)
return NS + "Sharp." + Name + "Native";
else
return "";
}
}
public override string CallByName (string var_name)
{
return var_name + ".NativeDelegate";
}
public override string FromNative (string var)
{
return NS + "Sharp." + Name + "Wrapper.GetManagedDelegate (" + var + ")";
}
public void WriteAccessors (StreamWriter sw, string indent, string var)
{
sw.WriteLine (indent + "get {");
sw.WriteLine (indent + "\treturn " + FromNative (var) + ";");
sw.WriteLine (indent + "}");
}
string CastFromInt (string type)
{
return type != "int" ? "(" + type + ") " : "";
}
string InvokeString {
get {
if (parms.Count == 0)
return String.Empty;
string[] result = new string [parms.Count];
for (int i = 0; i < parms.Count; i++) {
Parameter p = parms [i];
IGeneratable igen = p.Generatable;
if (i > 0 && parms [i - 1].IsString && p.IsLength) {
string string_name = parms [i - 1].Name;
result[i] = igen.CallByName (CastFromInt (p.CSType) + "System.Text.Encoding.UTF8.GetByteCount (" + string_name + ")");
continue;
}
p.CallName = p.Name;
result [i] = p.CallString;
if (p.IsUserData)
result [i] = "__data";
}
return String.Join (", ", result);
}
}
MethodBody body;
void GenInvoker (GenerationInfo gen_info, StreamWriter sw)
{
if (sig == null)
sig = new Signature (parms);
sw.WriteLine ("\tinternal class " + Name + "Invoker {");
sw.WriteLine ();
sw.WriteLine ("\t\t" + Name + "Native native_cb;");
sw.WriteLine ("\t\tIntPtr __data;");
sw.WriteLine ("\t\tGLib.DestroyNotify __notify;");
sw.WriteLine ();
sw.WriteLine ("\t\t~" + Name + "Invoker ()");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (__notify == null)");
sw.WriteLine ("\t\t\t\treturn;");
sw.WriteLine ("\t\t\t__notify (__data);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb) : this (native_cb, IntPtr.Zero, null) {}");
sw.WriteLine ();
sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb, IntPtr data) : this (native_cb, data, null) {}");
sw.WriteLine ();
sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb, IntPtr data, GLib.DestroyNotify notify)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tthis.native_cb = native_cb;");
sw.WriteLine ("\t\t\t__data = data;");
sw.WriteLine ("\t\t\t__notify = notify;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tinternal " + QualifiedName + " Handler {");
sw.WriteLine ("\t\t\tget {");
sw.WriteLine ("\t\t\t\treturn new " + QualifiedName + "(InvokeNative);");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t" + retval.CSType + " InvokeNative (" + sig + ")");
sw.WriteLine ("\t\t{");
body.Initialize (gen_info);
string call = "native_cb (" + InvokeString + ")";
if (retval.IsVoid)
sw.WriteLine ("\t\t\t" + call + ";");
else
sw.WriteLine ("\t\t\t" + retval.CSType + " result = " + retval.FromNative (call) + ";");
body.Finish (sw, String.Empty);
if (!retval.IsVoid)
sw.WriteLine ("\t\t\treturn result;");
sw.WriteLine ("\t\t}");
sw.WriteLine ("\t}");
sw.WriteLine ();
}
public string GenWrapper (GenerationInfo gen_info)
{
string wrapper = Name + "Native";
string qualname = MarshalType;
if (!Validate ())
return String.Empty;
body = new MethodBody (parms);
StreamWriter save_sw = gen_info.Writer;
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (qualname);
sw.WriteLine ("namespace " + NS + "Sharp {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ("\tusing System.Runtime.InteropServices;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
sw.WriteLine ("\t[GLib.CDeclCallback]");
sw.WriteLine ("\tinternal delegate " + retval.MarshalType + " " + wrapper + "(" + parms.ImportSignature + ");");
sw.WriteLine ();
GenInvoker (gen_info, sw);
sw.WriteLine ("\tinternal class " + Name + "Wrapper {");
sw.WriteLine ();
ManagedCallString call = new ManagedCallString (parms, false);
sw.WriteLine ("\t\tpublic " + retval.MarshalType + " NativeCallback (" + parms.ImportSignature + ")");
sw.WriteLine ("\t\t{");
string unconditional = call.Unconditional ("\t\t\t");
if (unconditional.Length > 0)
sw.WriteLine (unconditional);
sw.WriteLine ("\t\t\ttry {");
string call_setup = call.Setup ("\t\t\t\t");
if (call_setup.Length > 0)
sw.WriteLine (call_setup);
if (retval.CSType == "void")
sw.WriteLine ("\t\t\t\tmanaged ({0});", call);
else
sw.WriteLine ("\t\t\t\t{0} __ret = managed ({1});", retval.CSType, call);
string finish = call.Finish ("\t\t\t\t");
if (finish.Length > 0)
sw.WriteLine (finish);
sw.WriteLine ("\t\t\t\tif (release_on_call)\n\t\t\t\t\tgch.Free ();");
if (retval.CSType != "void")
sw.WriteLine ("\t\t\t\treturn {0};", retval.ToNative ("__ret"));
/* If the function expects one or more "out" parameters(error parameters are excluded) or has a return value different from void and bool, exceptions
* thrown in the managed function have to be considered fatal meaning that an exception is to be thrown and the function call cannot not return
*/
bool fatal = (retval.MarshalType != "void" && retval.MarshalType != "bool") || call.HasOutParam;
sw.WriteLine ("\t\t\t} catch (Exception e) {");
sw.WriteLine ("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (e, " + (fatal ? "true" : "false") + ");");
if (fatal) {
sw.WriteLine ("\t\t\t\t// NOTREACHED: Above call does not return.");
sw.WriteLine ("\t\t\t\tthrow e;");
} else if (retval.MarshalType == "bool") {
sw.WriteLine ("\t\t\t\treturn false;");
}
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tbool release_on_call = false;");
sw.WriteLine ("\t\tGCHandle gch;");
sw.WriteLine ();
sw.WriteLine ("\t\tpublic void PersistUntilCalled ()");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\trelease_on_call = true;");
sw.WriteLine ("\t\t\tgch = GCHandle.Alloc (this);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tinternal " + wrapper + " NativeDelegate;");
sw.WriteLine ("\t\t" + NS + "." + Name + " managed;");
sw.WriteLine ();
sw.WriteLine ("\t\tpublic " + Name + "Wrapper (" + NS + "." + Name + " managed)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tthis.managed = managed;");
sw.WriteLine ("\t\t\tif (managed != null)");
sw.WriteLine ("\t\t\t\tNativeDelegate = new " + wrapper + " (NativeCallback);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tpublic static " + NS + "." + Name + " GetManagedDelegate (" + wrapper + " native)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (native == null)");
sw.WriteLine ("\t\t\t\treturn null;");
sw.WriteLine ("\t\t\t" + Name + "Wrapper wrapper = (" + Name + "Wrapper) native.Target;");
sw.WriteLine ("\t\t\tif (wrapper == null)");
sw.WriteLine ("\t\t\t\treturn null;");
sw.WriteLine ("\t\t\treturn wrapper.managed;");
sw.WriteLine ("\t\t}");
sw.WriteLine ("\t}");
sw.WriteLine ("#endregion");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = save_sw;
return NS + "Sharp." + Name + "Wrapper";
}
public override void Generate (GenerationInfo gen_info)
{
gen_info.CurrentType = Name;
sig = new Signature (parms);
StreamWriter sw = gen_info.OpenStream (Name);
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ();
sw.WriteLine ("\t{0} delegate " + retval.CSType + " " + Name + "(" + sig.ToString() + ");", IsInternal ? "internal" : "public");
sw.WriteLine ();
sw.WriteLine ("}");
sw.Close ();
GenWrapper (gen_info);
Statistics.CBCount++;
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using DotNetMock.Dynamic;
using log4net;
using NUnit.Framework;
using Spring.Threading;
using Spring.Services.WindowsService.Common;
namespace Spring.Services.WindowsService.Common.Deploy.FileSystem
{
public abstract class FileSystemDeployLocationTestsBase
{
protected ILog log = LogManager.GetLogger (MethodBase.GetCurrentMethod ().DeclaringType);
protected string deployPath;
protected string deploy = "deploy";
protected string sampleDir, sampleDir2;
protected FileSystemDeployLocation location;
protected TestingHandler handler;
protected TestingHandler dontUseHandler;
protected IDeployEventDispatcher dispatcher;
protected ITrigger trigger;
protected string serviceXml;
protected string watcherXml;
protected Latch triggeredLatch;
protected void SetUp_ ()
{
deployPath = Guid.NewGuid ().ToString ();
sampleDir = Path.Combine (deployPath, deploy);
sampleDir2 = Path.Combine (deployPath, deploy + "2");
serviceXml = Path.Combine (sampleDir, Application.ServiceXml);
watcherXml = Path.Combine (sampleDir, Application.WatcherXml);
triggeredLatch = new Latch();
trigger = new ThreadingTimerTrigger (50);
trigger.Triggered += new EventHandler(trigger_Triggered);
dispatcher = new AggregatedDeployEventDispatcher (trigger);
TestUtils.ConfigureLog4Net ();
}
protected void AddApplication ()
{
AddApplication (sampleDir);
}
protected void AddApplication (string dir)
{
Directory.CreateDirectory (dir);
File.Copy("Data/Xml/watcher-1.xml", new Application(dir).WatcherXmlFullPath);
using (File.Create (Path.Combine (dir, Application.ServiceXml)))
{}
Assert.IsTrue (Directory.Exists (dir), "directory does not exist: " + dir);
}
protected void trigger_Triggered (object sender, EventArgs e)
{
triggeredLatch.Release();
}
protected void InitHandlerAndStartLocation (ISync sync)
{
GC.SuppressFinalize (location);
InitHandler (sync);
location.StartWatching ();
}
protected void InitHandler (ISync sync)
{
location = new FileSystemDeployLocation (dispatcher, deployPath);
handler = NewHandler (sync);
}
protected TestingHandler NewHandler (ISync sync)
{
try
{
log.Debug("disconnecting testing handler");
location.DeployEvent -= new DeployEventHandler (dontUseHandler.Handle);
}
catch
{}
dontUseHandler = new TestingHandler (sync);
log.Debug("connecting testing handler");
location.DeployEvent += new DeployEventHandler (dontUseHandler.Handle);
return dontUseHandler;
}
public void TearDown_ ()
{
log.Debug("disposing location ");
if (location != null)
{
location.Dispose ();
}
try
{
TestUtils.SafeDeleteDirectory(Path.GetFullPath (deployPath));
}
catch (Exception e)
{
log.Error("deploy folder not deleted", e);
}
try
{
TestUtils.SafeDeleteDirectory(Path.GetFullPath (deployPath));
}
catch (Exception e)
{
log.Error("test folder not deleted", e);
}
Assert.IsFalse(Directory.Exists(Path.GetFullPath (deployPath)), "the root of the deploy directory still exist");
}
}
[TestFixture]
public class FileSystemDeployLocationTest_Mocked : FileSystemDeployLocationTestsBase
{
private DynamicMock factoryMock;
private DynamicMock watcherMock;
private IApplicationWatcherFactory factory;
private IApplicationWatcher watcher;
private bool deployEventDispatched;
private ISync forwardDispatcherSync;
[SetUp]
public void SetUp ()
{
base.SetUp_();
factoryMock = new DynamicMock(typeof(IApplicationWatcherFactory));
watcherMock = new DynamicMock(typeof(IApplicationWatcher));
factory = (IApplicationWatcherFactory) factoryMock.Object;
watcher = (IApplicationWatcher) watcherMock.Object;
deployEventDispatched = false;
forwardDispatcherSync = new Latch();
}
[TearDown]
public void TearDown ()
{
base.TearDown_();
factoryMock.Verify();
watcherMock.Verify();
}
[Test]
public void DisposeDispatcherOnDispose ()
{
DynamicMock mock = new DynamicMock (typeof (IDeployEventDispatcher));
IDeployEventDispatcher dispatcher = (IDeployEventDispatcher) mock.Object;
mock.Expect ("Dispose");
IDeployLocation location = new FileSystemDeployLocation (dispatcher, deployPath);
location.Dispose ();
mock.Verify ();
}
[Test]
public void ANewWatcherGetsCreatedAndAssociatedToAnyExistingApplication ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
AddApplication ();
location = new FileSystemDeployLocation (new ForwardingDeployEventDispatcher(), factory, deployPath, true);
}
[Test]
public void TheAssociatedWatcherIsStoppedAndDisposedWhenAnApplicationGetsRemoved ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
watcherMock.Expect("StopWatching");
watcherMock.Expect("Dispose");
AddApplication();
location = new FileSystemDeployLocation (new ForwardingDeployEventDispatcher(), factory, deployPath, true);
Directory.Delete(sampleDir, true);
triggeredLatch.Acquire();
}
[Test]
public void TheAssociatedWatcherIsStoppedAndDisposedOnDispose ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
watcherMock.Expect("StopWatching");
watcherMock.Expect("Dispose");
AddApplication();
location = new FileSystemDeployLocation (new ForwardingDeployEventDispatcher(), factory, deployPath, true);
triggeredLatch.Acquire();
location.Dispose();
}
[Test]
public void IgnoresExceptionAddingExistingApplication ()
{
factoryMock.ExpectAndThrow("CreateApplicationWatcherMonitor", new Exception("exception generated to test behaviour adding application"));
AddApplication();
location = new FileSystemDeployLocation (new ForwardingDeployEventDispatcher(), factory, deployPath, true);
}
[Test] // Bug fix
public void NotInfiniteLoopRemovingAnApplicationWithAManagerThatThrowsExceptionWhenStopped ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
watcherMock.ExpectAndThrow("StopWatching", new Exception());
AddApplication();
ForwardingDeployEventDispatcher dispatcher = new ForwardingDeployEventDispatcher();
dispatcher.DeployEvent += new DeployEventHandler(dispatcher_DeployEvent);
location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
Directory.Delete(sampleDir, true);
forwardDispatcherSync.Acquire();
Assert.IsTrue(deployEventDispatched, "removal not dispatched in case of error on application watcher");
}
[Test] // Bug fix
public void NotInfiniteLoopRemovingAnApplicationWithAManagerThatThrowsExceptionWhenDisposed ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
watcherMock.Expect("StopWatching");
watcherMock.ExpectAndThrow("Dispose", new Exception());
AddApplication();
ForwardingDeployEventDispatcher dispatcher = new ForwardingDeployEventDispatcher();
dispatcher.DeployEvent += new DeployEventHandler(dispatcher_DeployEvent);
location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
Directory.Delete(sampleDir, true);
forwardDispatcherSync.Acquire();
Assert.IsTrue(deployEventDispatched, "removal not dispatched in case of error on application watcher");
}
class ExceptionDispatcher : IDeployEventDispatcher
{
public event DeployEventHandler DeployEvent;
ISync started, canContinue;
public ExceptionDispatcher (ISync started, ISync canContinue)
{
this.started = started;
this.canContinue = canContinue;
}
public void Dispose ()
{
}
public void Dispatch (IDeployLocation sender, DeployEventType eventType, IApplication application)
{
if (DeployEvent != null) DeployEvent(null, new DeployEventArgs(application, eventType));
started.Release();
canContinue.Acquire();
throw new Exception ("this dispatcher is for testing and always raises exception");
}
}
[Test]
public void IgnoreExceptionOnDispatcherWhenAdding ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
ISync canContinue = new Semaphore(0);
ISync started = new Semaphore(0);
IDeployEventDispatcher dispatcher = new ExceptionDispatcher(started, canContinue);
location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
AddApplication();
started.Acquire();
canContinue.Release();
Assert.AreEqual(1, location.Applications.Count);
AddApplication(sampleDir2);
started.Acquire();
canContinue.Release();
Assert.AreEqual(2, location.Applications.Count);
}
[Test]
public void IgnoreExceptionOnDispatcherWhenRemoving ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.Expect("StartWatching");
watcherMock.Expect("StopWatching");
watcherMock.Expect("Dispose");
watcherMock.Expect("StartWatching");
watcherMock.Expect("StopWatching");
watcherMock.Expect("Dispose");
ISync canContinue = new Semaphore(0);
ISync started = new Semaphore(0);
AddApplication();
AddApplication(sampleDir2);
IDeployEventDispatcher dispatcher = new ExceptionDispatcher(started, canContinue);
location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
Assert.AreEqual(2, location.Applications.Count);
Directory.Delete(sampleDir, true);
started.Acquire();
canContinue.Release();
Assert.AreEqual(1, location.Applications.Count);
Directory.Delete(sampleDir2, true);
started.Acquire();
canContinue.Release();
Assert.AreEqual(0, location.Applications.Count);
}
[Test]
public void OnlyApplicationsWithAManagerSuccesfullyStartedAreListed ()
{
factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
watcherMock.ExpectAndThrow("StartWatching", new Exception());
AddApplication();
dispatcher.DeployEvent += new DeployEventHandler(dispatcher_DeployEvent);
location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
triggeredLatch.Acquire();
Assert.AreEqual(0, location.Applications.Count);
Assert.IsFalse(deployEventDispatched, "add dispatched in case of error on application watcher");
}
private void dispatcher_DeployEvent (object sender, DeployEventArgs args)
{
deployEventDispatched = true;
forwardDispatcherSync.Release();
}
}
[TestFixture]
public class FileSystemDeployLocationTest : FileSystemDeployLocationTestsBase
{
[SetUp]
public void SetUp ()
{
base.SetUp_ ();
InitHandler (new NullSync ());
}
[TearDown]
public void TearDown ()
{
log.Debug("tear down");
base.TearDown_();
}
private void AddInvalidApplication ()
{
Directory.CreateDirectory (sampleDir);
Assert.IsTrue (Directory.Exists (sampleDir), "directory does not exist: " + sampleDir);
}
[Test]
public void CreateDeployLocationPath ()
{
Assert.IsTrue (Directory.Exists (location.FullPath));
Assert.AreEqual (0, location.Applications.Count);
}
[Test]
public void ListExistingDirectoriesAsApplications ()
{
log.Debug ("start ListExistingDirectoriesAsApplications");
AddApplication ();
location = new FileSystemDeployLocation (deployPath);
Assert.AreEqual (1, location.Applications.Count);
log.Debug ("end ListExistingDirectoriesAsApplications");
}
[Test]
public void CreateAFileToPreventDeployDirectoryDeletion ()
{
location.StartWatching ();
Assert.IsTrue (File.Exists (location.LockFileName));
}
[Test]
public void LockFileIsDeletedOnDisposeOrStop ()
{
FileSystemDeployLocation location =
new FileSystemDeployLocation (dispatcher, deployPath);
location.StartWatching ();
location.Dispose();
Assert.IsFalse (File.Exists (location.LockFileName));
}
[Test]
public void RaiseEventAddingAnApplication ()
{
Semaphore sync = new Semaphore (0);
InitHandlerAndStartLocation (sync);
AddApplication ();
sync.Acquire ();
Assert.IsTrue (handler.applicationAdded, "application not added");
Assert.AreEqual (1, location.Applications.Count);
}
[Test]
public void RaiseEventRemovingAnApplication ()
{
AddApplication ();
Semaphore sync = new Semaphore (0);
InitHandlerAndStartLocation (sync);
Directory.Delete (sampleDir, true);
Thread.SpinWait(1);
Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
log.Debug("directory deleted");
sync.Acquire ();
log.Debug("sync acquired");
Assert.IsFalse (Directory.Exists (sampleDir), "directory still exists: " + sampleDir);
Assert.IsTrue (handler.applicationRemoved, "application not removed");
Assert.AreEqual (0, location.Applications.Count);
}
[Test]
public void RenamingADirectoryHostingAnApplicationItEqualsRemoveOldApplicationAndAddUnderNewName ()
{
Semaphore sync = new Semaphore (0);
InitHandlerAndStartLocation (sync);
AddApplication ();
sync.Acquire ();
Assert.IsTrue (handler.applicationAdded, "application not added");
Directory.Move (sampleDir, sampleDir2);
sync.Acquire (); // add or remove
sync.Acquire (); // add or remove
Assert.IsTrue (handler.applicationRemoved, "application was not removed");
}
//[Test, Ignore("Gets stuck when running entire WindowsService.Tests dll")]
[Test]
public void EventsAreRaisedOnlyForValidatedApplication ()
{
Semaphore sync = new Semaphore (0);
InitHandlerAndStartLocation (sync);
AddInvalidApplication ();
triggeredLatch.Acquire();
Assert.IsFalse (handler.applicationAdded, "invalid application was added");
Assert.AreEqual (0, location.Applications.Count, "invalid application was added");
}
[Test]
public void RemoveAfterSpringAssemblyDeploy ()
{
Semaphore sync = new Semaphore (0);
InitHandlerAndStartLocation (sync);
AddApplication();
sync.Acquire();
string springPrivateBin = Path.Combine(sampleDir, SpringAssembliesDeployer.PrivateBinPathPrefix);
Directory.CreateDirectory(springPrivateBin);
using (File.Create(Path.Combine(springPrivateBin, "foo.dll"))) {}
Directory.Delete(sampleDir, true);
Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
log.Debug (String.Format ("directory {0} removed to simulate application removal", sampleDir));
sync.Acquire();
Assert.IsTrue (handler.applicationRemoved, "application not removed");
Assert.AreEqual (0, location.Applications.Count, "application not removed");
}
[Test]
public void AddingRemovingUpdatingOrRenamingAFileUnderAnApplicationDirectoryItGetsUpdated ()
{
Semaphore sync = new Semaphore (0);
AddApplication();
InitHandlerAndStartLocation (sync);
string subDir = Path.Combine(sampleDir, "foo");
Directory.CreateDirectory(subDir);
string aFile = Path.Combine(subDir, "foo.bar");
sync.Acquire();
// create
log.Debug (String.Format ("creating a file"));
using (File.Create(aFile)) {}
sync.Acquire();
Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");
// update
log.Debug (String.Format ("updating a file"));
handler.applicationUpdated = false;
File.SetLastWriteTime(aFile, DateTime.Now);
sync.Acquire();
Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");
// delete
log.Debug (String.Format ("deleting a file"));
handler.applicationUpdated = false;
File.Delete(aFile);
sync.Acquire();
Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");
}
[Test]
public void CanBeDisposedMoreThanOnce ()
{
IDeployLocation location = new FileSystemDeployLocation(dispatcher,
DefaultApplicationWatcherFactory.Instance, deployPath, true);
location.Dispose();
location.Dispose();
}
[Test]
[ExpectedException(typeof(ObjectDisposedException))]
public void CanBeStartedExplicitlyStartedButIsImplicitlyStoppedWhenDisposed ()
{
FileSystemDeployLocation location = new FileSystemDeployLocation(deployPath);
location.StartWatching();
location.Dispose();
location.StartWatching();
}
[Test]
public void EventsRelatedToFilesInDeployPathAreIgnored ()
{
FieldInfo f = location.GetType().GetField("_fileSystemWatcher",
BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(f);
//FileSystemWatcher watcher = (FileSystemWatcher) f.GetValue(location);
FileSystemMonitor watcher = (FileSystemMonitor) f.GetValue(location);
Assert.IsNotNull(watcher);
Assert.AreEqual(NotifyFilters.DirectoryName | NotifyFilters.Attributes, watcher.NotifyFilter);
Assert.AreEqual(
Enum.Parse(typeof(NotifyFilters), 0.ToString()) ,
watcher.NotifyFilter & NotifyFilters.FileName);
}
[Test]
public void AnInvalidApplicationIsNotUpdatedNorRemovedButItWillNotBeListed ()
{
Semaphore sync = new Semaphore (0);
AddApplication();
InitHandlerAndStartLocation (sync);
File.Delete(serviceXml);
Assert.IsFalse(sync.Attempt(1000), "some events propagated, expecting no one");
Assert.IsFalse (handler.applicationUpdated, "application wrongly updated");
Assert.IsFalse(handler.applicationRemoved, "application wrongly removed");
Assert.AreEqual (0, location.Applications.Count, "application listed");
location.Dispose();
location = new FileSystemDeployLocation (deployPath);
Assert.AreEqual (0, location.Applications.Count, "invalid application listed");
}
[Test]
public void AnInvalidApplicationIsNotUpdatedNorRemovedButWhenRemovedStillRaisesTheRemovedEvent ()
{
Semaphore sync = new Semaphore (0);
AddApplication();
InitHandlerAndStartLocation (sync);
File.Delete(serviceXml);
Assert.IsFalse(sync.Attempt(1000), "some events propagated, expecting no one");
// remove
TestUtils.SafeDeleteDirectory(sampleDir);
Thread.SpinWait(1);
Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
log.Debug("directory deleted");
sync.Acquire ();
log.Debug("sync acquired");
Assert.IsFalse (Directory.Exists (sampleDir), "directory still exists: " + sampleDir);
Assert.IsTrue (handler.applicationRemoved, "application not removed");
Assert.AreEqual (0, location.Applications.Count);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CampaignSharedSet</c> resource.</summary>
public sealed partial class CampaignSharedSetName : gax::IResourceName, sys::IEquatable<CampaignSharedSetName>
{
/// <summary>The possible contents of <see cref="CampaignSharedSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>
/// .
/// </summary>
CustomerCampaignSharedSet = 1,
}
private static gax::PathTemplate s_customerCampaignSharedSet = new gax::PathTemplate("customers/{customer_id}/campaignSharedSets/{campaign_id_shared_set_id}");
/// <summary>Creates a <see cref="CampaignSharedSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CampaignSharedSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignSharedSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignSharedSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignSharedSetName"/> with the pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignSharedSetName"/> constructed from the provided ids.</returns>
public static CampaignSharedSetName FromCustomerCampaignSharedSet(string customerId, string campaignId, string sharedSetId) =>
new CampaignSharedSetName(ResourceNameType.CustomerCampaignSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string sharedSetId) =>
FormatCustomerCampaignSharedSet(customerId, campaignId, sharedSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </returns>
public static string FormatCustomerCampaignSharedSet(string customerId, string campaignId, string sharedSetId) =>
s_customerCampaignSharedSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSharedSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignSharedSetName"/> if successful.</returns>
public static CampaignSharedSetName Parse(string campaignSharedSetName) => Parse(campaignSharedSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSharedSetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CampaignSharedSetName"/> if successful.</returns>
public static CampaignSharedSetName Parse(string campaignSharedSetName, bool allowUnparsed) =>
TryParse(campaignSharedSetName, allowUnparsed, out CampaignSharedSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignSharedSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignSharedSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignSharedSetName, out CampaignSharedSetName result) =>
TryParse(campaignSharedSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignSharedSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignSharedSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignSharedSetName, bool allowUnparsed, out CampaignSharedSetName result)
{
gax::GaxPreconditions.CheckNotNull(campaignSharedSetName, nameof(campaignSharedSetName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignSharedSet.TryParseName(campaignSharedSetName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignSharedSet(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignSharedSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CampaignSharedSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string sharedSetId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
SharedSetId = sharedSetId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignSharedSetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignSharedSetName(string customerId, string campaignId, string sharedSetId) : this(ResourceNameType.CustomerCampaignSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SharedSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SharedSetId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignSharedSet: return s_customerCampaignSharedSet.Expand(CustomerId, $"{CampaignId}~{SharedSetId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CampaignSharedSetName);
/// <inheritdoc/>
public bool Equals(CampaignSharedSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignSharedSetName a, CampaignSharedSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignSharedSetName a, CampaignSharedSetName b) => !(a == b);
}
public partial class CampaignSharedSet
{
/// <summary>
/// <see cref="CampaignSharedSetName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CampaignSharedSetName ResourceNameAsCampaignSharedSetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CampaignSharedSetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="SharedSetName"/>-typed view over the <see cref="SharedSet"/> resource name property.
/// </summary>
internal SharedSetName SharedSetAsSharedSetName
{
get => string.IsNullOrEmpty(SharedSet) ? null : SharedSetName.Parse(SharedSet, allowUnparsed: true);
set => SharedSet = value?.ToString() ?? "";
}
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using Leap.Unity.Space;
using Leap.Unity.Query;
using Leap.Unity.Attributes;
namespace Leap.Unity.GraphicalRenderer {
[LeapGraphicTag("Baked")]
[Serializable]
public class LeapBakedRenderer : LeapMesherBase {
public const string DEFAULT_SHADER = "LeapMotion/GraphicRenderer/Unlit/Baked";
#region INSPECTOR FIELDS
[Tooltip("What type of graphic motion should be supported by this renderer? Currently there are only two modes, None, and Translation.")]
[EditTimeOnly]
[SerializeField]
private MotionType _motionType = MotionType.Translation;
[Tooltip("Should the baked renderer create an actual game object and attach a mesh renderer to it in order to display the graphics?")]
[EditTimeOnly]
[SerializeField]
private bool _createMeshRenderers;
#endregion
#region PRIVATE VARIABLES
[SerializeField, HideInInspector]
private List<MeshRendererContainer> _renderers = new List<MeshRendererContainer>();
//## Rect space
private const string RECT_POSITIONS = LeapGraphicRenderer.PROPERTY_PREFIX + "Rect_GraphicPositions";
private List<Vector4> _rect_graphicPositions = new List<Vector4>();
//## Cylindrical/Spherical spaces
private const string CURVED_PARAMETERS = LeapGraphicRenderer.PROPERTY_PREFIX + "Curved_GraphicParameters";
private List<Vector4> _curved_graphicParameters = new List<Vector4>();
//## Cache data to be used inside of graphicVertToMeshVert
private Matrix4x4 _translation_graphicVertToMeshVert;
private Matrix4x4 _noMotion_graphicVertToLocalVert;
private ITransformer _noMotion_transformer;
#endregion
public enum MotionType {
None,
Translation
}
public override SupportInfo GetSpaceSupportInfo(LeapSpace space) {
if (space == null ||
space is LeapCylindricalSpace ||
space is LeapSphericalSpace) {
return SupportInfo.FullSupport();
} else {
return SupportInfo.Error("Baked Renderer does not support " + space.GetType().Name);
}
}
public override void OnEnableRenderer() {
base.OnEnableRenderer();
foreach (var renderer in _renderers) {
renderer.ClearPropertyBlock();
}
}
public override void OnUpdateRenderer() {
base.OnUpdateRenderer();
if (_motionType != MotionType.None) {
if (renderer.space == null) {
using (new ProfilerSample("Build Material Data")) {
_rect_graphicPositions.Clear();
foreach (var graphic in group.graphics) {
var localSpace = renderer.transform.InverseTransformPoint(graphic.transform.position);
_rect_graphicPositions.Add(localSpace);
}
}
using (new ProfilerSample("Upload Material Data")) {
_material.SetVectorArraySafe(RECT_POSITIONS, _rect_graphicPositions);
}
} else if (renderer.space is LeapRadialSpace) {
var radialSpace = renderer.space as LeapRadialSpace;
using (new ProfilerSample("Build Material Data")) {
_curved_graphicParameters.Clear();
foreach (var graphic in group.graphics) {
var t = graphic.anchor.transformer as IRadialTransformer;
_curved_graphicParameters.Add(t.GetVectorRepresentation(graphic.transform));
}
}
using (new ProfilerSample("Upload Material Data")) {
_material.SetFloat(SpaceProperties.RADIAL_SPACE_RADIUS, radialSpace.radius);
_material.SetVectorArraySafe(CURVED_PARAMETERS, _curved_graphicParameters);
}
}
}
if (!_createMeshRenderers) {
using (new ProfilerSample("Draw Meshes")) {
for (int i = 0; i < _meshes.Count; i++) {
drawMesh(_meshes[i], renderer.transform.localToWorldMatrix);
}
}
}
}
#if UNITY_EDITOR
public override void OnEnableRendererEditor() {
base.OnEnableRendererEditor();
_shader = Shader.Find(DEFAULT_SHADER);
}
public override void OnDisableRendererEditor() {
base.OnDisableRendererEditor();
foreach (var renderer in _renderers) {
renderer.Destroy();
}
_renderers.Clear();
}
public override void OnUpdateRendererEditor() {
base.OnUpdateRendererEditor();
if (_renderers == null) {
_renderers = new List<MeshRendererContainer>();
}
if (_createMeshRenderers) {
for (int i = _renderers.Count; i-- != 0;) {
if (_renderers[i].obj == null) {
_renderers.RemoveAt(i);
}
}
while (_renderers.Count > _meshes.Count) {
_renderers.RemoveLast().Destroy();
}
while (_renderers.Count < _meshes.Count) {
_renderers.Add(new MeshRendererContainer(renderer.transform));
}
for (int i = 0; i < _meshes.Count; i++) {
_renderers[i].MakeValid(renderer.transform, i, _meshes[i], _material, _spriteTextureBlock);
}
} else {
while (_renderers.Count > 0) {
_renderers.RemoveLast().Destroy();
}
}
}
#endif
protected override void prepareMaterial() {
if (_shader == null) {
_shader = Shader.Find(DEFAULT_SHADER);
}
base.prepareMaterial();
switch (_motionType) {
case MotionType.Translation:
_material.EnableKeyword(LeapGraphicRenderer.FEATURE_MOVEMENT_TRANSLATION);
break;
}
if (_motionType != MotionType.None) {
if (renderer.space is LeapCylindricalSpace) {
_material.EnableKeyword(SpaceProperties.CYLINDRICAL_FEATURE);
} else if (renderer.space is LeapSphericalSpace) {
_material.EnableKeyword(SpaceProperties.SPHERICAL_FEATURE);
}
}
}
protected override void buildTopology() {
//If the next graphic is going to put us over the limit, finish the current mesh
//and start a new one.
if (_generation.verts.Count + _generation.graphic.mesh.vertexCount > MeshUtil.MAX_VERT_COUNT) {
finishAndAddMesh();
beginMesh();
}
switch (_motionType) {
case MotionType.None:
_noMotion_transformer = _generation.graphic.transformer;
_noMotion_graphicVertToLocalVert = renderer.transform.worldToLocalMatrix *
_generation.graphic.transform.localToWorldMatrix;
break;
case MotionType.Translation:
_translation_graphicVertToMeshVert = Matrix4x4.TRS(-renderer.transform.InverseTransformPoint(_generation.graphic.transform.position),
Quaternion.identity,
Vector3.one) *
renderer.transform.worldToLocalMatrix *
_generation.graphic.transform.localToWorldMatrix;
break;
default:
throw new NotImplementedException();
}
base.buildTopology();
}
protected override void postProcessMesh() {
base.postProcessMesh();
//For the baked renderer, the mesh really never accurately represents it's visual position
//or size, so just disable culling entirely by making the bound gigantic.
_generation.mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 100000);
}
protected override bool doesRequireVertInfo() {
if (_motionType != MotionType.None) {
return true;
}
return base.doesRequireVertInfo();
}
protected override Vector3 graphicVertToMeshVert(Vector3 vertex) {
switch (_motionType) {
case MotionType.None:
var localVert = _noMotion_graphicVertToLocalVert.MultiplyPoint3x4(vertex);
return _noMotion_transformer.TransformPoint(localVert);
case MotionType.Translation:
return _translation_graphicVertToMeshVert.MultiplyPoint3x4(vertex);
}
throw new NotImplementedException();
}
protected override void graphicVertNormalToMeshVertNormal(Vector3 vertex,
Vector3 normal,
out Vector3 meshVert,
out Vector3 meshNormal) {
switch (_motionType) {
case MotionType.None:
var localVert = _noMotion_graphicVertToLocalVert.MultiplyPoint3x4(vertex);
var localNormal = _noMotion_graphicVertToLocalVert.MultiplyVector(normal);
var matrix = _noMotion_transformer.GetTransformationMatrix(localVert);
meshVert = matrix.MultiplyPoint3x4(Vector3.zero);
meshNormal = matrix.MultiplyVector(localNormal);
return;
case MotionType.Translation:
meshVert = _translation_graphicVertToMeshVert.MultiplyPoint3x4(vertex);
meshNormal = _translation_graphicVertToMeshVert.MultiplyVector(normal);
return;
}
throw new NotImplementedException();
}
[Serializable]
protected class MeshRendererContainer {
public GameObject obj;
public MeshFilter filter;
public MeshRenderer renderer;
public MeshRendererContainer(Transform root) {
obj = new GameObject("Graphic Renderer");
#if UNITY_EDITOR
Undo.RegisterCreatedObjectUndo(obj, "Created graphic renderer");
#endif
filter = null;
renderer = null;
}
public void Destroy() {
#if UNITY_EDITOR
if (!Application.isPlaying) {
Undo.DestroyObjectImmediate(obj);
} else
#endif
{
UnityEngine.Object.Destroy(obj);
}
}
public void MakeValid(Transform root, int index, Mesh mesh, Material material, MaterialPropertyBlock block) {
obj.transform.SetParent(root);
obj.transform.SetSiblingIndex(index);
obj.SetActive(true);
obj.transform.localPosition = Vector3.zero;
obj.transform.localRotation = Quaternion.identity;
obj.transform.localScale = Vector3.one;
if (filter == null) {
filter = InternalUtility.AddComponent<MeshFilter>(obj);
}
filter.sharedMesh = mesh;
if (renderer == null) {
renderer = InternalUtility.AddComponent<MeshRenderer>(obj);
}
renderer.enabled = true;
renderer.sharedMaterial = material;
renderer.SetPropertyBlock(block);
}
public void ClearPropertyBlock() {
renderer.SetPropertyBlock(new MaterialPropertyBlock());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.IO.Tests
{
public class Directory_Delete_str : FileSystemTest
{
#region Utilities
public virtual void Delete(string path)
{
Directory.Delete(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullParameters()
{
Assert.Throws<ArgumentNullException>(() => Delete(null));
}
[Fact]
public void InvalidParameters()
{
Assert.Throws<ArgumentException>(() => Delete(string.Empty));
}
[Fact]
public void ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName));
}
Assert.True(testDir.Exists);
}
[Fact]
public void ShouldThrowIOExceptionForDirectoryWithFiles()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
public void DirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
[OuterLoop]
public void DeleteRoot()
{
Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory())));
}
[Fact]
public void PositiveTest()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsDirectoryNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Fact]
public void ShouldThrowIOExceptionDeletingCurrentDirectory()
{
Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory()));
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void DeletingSymLinkDoesntDeleteTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
Directory.CreateDirectory(path);
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
// Both the symlink and the target exist
Assert.True(Directory.Exists(path), "path should exist");
Assert.True(Directory.Exists(linkPath), "linkPath should exist");
// Delete the symlink
Directory.Delete(linkPath);
// Target should still exist
Assert.True(Directory.Exists(path), "path should still exist");
Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist");
}
[ConditionalFact(nameof(UsingNewNormalization))]
public void ExtendedDirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
public void LongPathExtendedDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500));
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException
public void WindowsDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException
public void WindowsDeleteExtendedReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds
public void UnixDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds
public void WindowsShouldBeAbleToDeleteHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds
public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds
public void UnixShouldBeAbleToDeleteHiddenDirectory()
{
string testDir = "." + GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, testDir));
Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden));
Delete(Path.Combine(TestDirectory, testDir));
Assert.False(Directory.Exists(testDir));
}
[Fact]
[OuterLoop("Needs sudo access")]
[PlatformSpecific(TestPlatforms.Linux)]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_NotFoundDirectory_ReadOnlyVolume()
{
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(readOnlyDirectory, "DoesNotExist")));
});
}
#endregion
}
public class Directory_Delete_str_bool : Directory_Delete_str
{
#region Utilities
public override void Delete(string path)
{
Directory.Delete(path, false);
}
public virtual void Delete(string path, bool recursive)
{
Directory.Delete(path, recursive);
}
#endregion
[Fact]
public void RecursiveDelete()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
testDir.CreateSubdirectory(GetTestFileName());
Delete(testDir.FullName, true);
Assert.False(testDir.Exists);
}
[Fact]
public void RecursiveDeleteWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName + Path.DirectorySeparatorChar, true);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file
public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName, true));
}
Assert.True(testDir.Exists);
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace ThirdParty.Ionic.Zlib
{
/// <summary>
/// Calculates a 32bit Cyclic Redundancy Checksum (CRC) using the
/// same polynomial used by Zip. This type is used internally by DotNetZip; it is generally not used directly
/// by applications wishing to create, read, or manipulate zip archive files.
/// </summary>
internal class CRC32
{
/// <summary>
/// indicates the total number of bytes read on the CRC stream.
/// This is used when writing the ZipDirEntry when compressing files.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
// return one's complement of the running result
return unchecked((Int32)(~_RunningCrc32Result));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
unchecked
{
//UInt32 crc32Result;
//crc32Result = 0xFFFFFFFF;
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
//for (int i = 0; i < count; i++)
//{
// _RunningCrc32Result = ((_RunningCrc32Result) >> 8) ^ crc32Table[(buffer[i]) ^ ((_RunningCrc32Result) & 0x000000FF)];
//}
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_RunningCrc32Result);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo.
/// This is a computation defined by PKzip.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
for (int i = 0; i < count; i++)
{
int x = offset + i;
_RunningCrc32Result = ((_RunningCrc32Result) >> 8) ^ crc32Table[(block[x]) ^ ((_RunningCrc32Result) & 0x000000FF)];
}
_TotalBytesRead += count;
}
// pre-initialize the crc table for speed of lookup.
static CRC32()
{
unchecked
{
// This is the official polynomial used by CRC32 in PKZip.
// Often the polynomial is shown reversed as 0x04C11DB7.
UInt32 dwPolynomial = 0xEDB88320;
UInt32 i, j;
crc32Table = new UInt32[256];
UInt32 dwCrc;
for (i = 0; i < 256; i++)
{
dwCrc = i;
for (j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
crc32Table[i] = dwCrc;
}
}
}
// private member vars
private Int64 _TotalBytesRead;
private static UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _RunningCrc32Result = 0xFFFFFFFF;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when reading from a stream,
/// or to calculate a CRC when writing to a stream. The stream should be used to either
/// read, or write, but not both. If you intermix reads and writes, the results are
/// not defined.
/// </para>
/// <para>This class is intended primarily for use internally by the DotNetZip library.</para>
/// </remarks>
public class CrcCalculatorStream : System.IO.Stream
{
private System.IO.Stream _InnerStream;
private CRC32 _Crc32;
private Int64 _length = 0;
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number
/// of bytes written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// The constructor.
/// </summary>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: base()
{
_InnerStream = stream;
_Crc32 = new CRC32();
}
/// <summary>
/// The constructor.
/// </summary>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: base()
{
_InnerStream = stream;
_Crc32 = new CRC32();
_length = length;
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have a definite length.
// This is especially useful when returning a stream for the uncompressed data directly to the
// application. The app won't necessarily read only the UncompressedSize number of bytes.
// For example wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a corrupt string.
// The length limits that, prevents that problem.
if (_length != 0)
{
if (_Crc32.TotalBytesRead >= _length) return 0; // EOF
Int64 bytesRemaining = _length - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _InnerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_InnerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _InnerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
public override bool CanSeek
{
get { return _InnerStream.CanSeek; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _InnerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_InnerStream.Flush();
}
/// <summary>
/// Not implemented.
/// </summary>
public override long Length
{
get
{
if (_length == 0) throw new NotImplementedException();
else return _length;
}
}
/// <summary>
/// Not implemented.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Not implemented.
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented.
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
}
}
| |
namespace NXTTest
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if ( disposing && ( components != null ) )
{
components.Dispose( );
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent( )
{
this.components = new System.ComponentModel.Container( );
this.groupBox1 = new System.Windows.Forms.GroupBox( );
this.disconnectButton = new System.Windows.Forms.Button( );
this.connectButton = new System.Windows.Forms.Button( );
this.portBox = new System.Windows.Forms.TextBox( );
this.label1 = new System.Windows.Forms.Label( );
this.groupBox2 = new System.Windows.Forms.GroupBox( );
this.batteryLevelBox = new System.Windows.Forms.TextBox( );
this.label8 = new System.Windows.Forms.Label( );
this.freeUserFlashBox = new System.Windows.Forms.TextBox( );
this.label7 = new System.Windows.Forms.Label( );
this.btSignalStrengthBox = new System.Windows.Forms.TextBox( );
this.label6 = new System.Windows.Forms.Label( );
this.btAddressBox = new System.Windows.Forms.TextBox( );
this.label5 = new System.Windows.Forms.Label( );
this.deviceNameBox = new System.Windows.Forms.TextBox( );
this.label4 = new System.Windows.Forms.Label( );
this.protocolBox = new System.Windows.Forms.TextBox( );
this.label3 = new System.Windows.Forms.Label( );
this.firmwareBox = new System.Windows.Forms.TextBox( );
this.label2 = new System.Windows.Forms.Label( );
this.groupBox3 = new System.Windows.Forms.GroupBox( );
this.rotationCountBox = new System.Windows.Forms.TextBox( );
this.label16 = new System.Windows.Forms.Label( );
this.blockTachoCountBox = new System.Windows.Forms.TextBox( );
this.label15 = new System.Windows.Forms.Label( );
this.tachoCountBox = new System.Windows.Forms.TextBox( );
this.label14 = new System.Windows.Forms.Label( );
this.groupBox4 = new System.Windows.Forms.GroupBox( );
this.runStateCombo = new System.Windows.Forms.ComboBox( );
this.label13 = new System.Windows.Forms.Label( );
this.regulationModeCombo = new System.Windows.Forms.ComboBox( );
this.label12 = new System.Windows.Forms.Label( );
this.groupBox5 = new System.Windows.Forms.GroupBox( );
this.modeRegulatedBox = new System.Windows.Forms.CheckBox( );
this.modeBrakeCheck = new System.Windows.Forms.CheckBox( );
this.modeOnCheck = new System.Windows.Forms.CheckBox( );
this.tachoLimitBox = new System.Windows.Forms.TextBox( );
this.label11 = new System.Windows.Forms.Label( );
this.turnRatioUpDown = new System.Windows.Forms.NumericUpDown( );
this.label10 = new System.Windows.Forms.Label( );
this.label9 = new System.Windows.Forms.Label( );
this.powerUpDown = new System.Windows.Forms.NumericUpDown( );
this.getMotorStateButton = new System.Windows.Forms.Button( );
this.setMotorStateButton = new System.Windows.Forms.Button( );
this.resetMotorButton = new System.Windows.Forms.Button( );
this.motorCombo = new System.Windows.Forms.ComboBox( );
this.toolTip = new System.Windows.Forms.ToolTip( this.components );
this.groupBox6 = new System.Windows.Forms.GroupBox( );
this.setInputModeButton = new System.Windows.Forms.Button( );
this.sensorModeCombo = new System.Windows.Forms.ComboBox( );
this.label25 = new System.Windows.Forms.Label( );
this.sensorTypeCombo = new System.Windows.Forms.ComboBox( );
this.label23 = new System.Windows.Forms.Label( );
this.label24 = new System.Windows.Forms.Label( );
this.calibratedInputBox = new System.Windows.Forms.TextBox( );
this.label22 = new System.Windows.Forms.Label( );
this.scaledInputBox = new System.Windows.Forms.TextBox( );
this.label21 = new System.Windows.Forms.Label( );
this.normalizedInputBox = new System.Windows.Forms.TextBox( );
this.label20 = new System.Windows.Forms.Label( );
this.rawInputBox = new System.Windows.Forms.TextBox( );
this.label19 = new System.Windows.Forms.Label( );
this.sensorModeBox = new System.Windows.Forms.TextBox( );
this.label18 = new System.Windows.Forms.Label( );
this.sensorTypeBox = new System.Windows.Forms.TextBox( );
this.label17 = new System.Windows.Forms.Label( );
this.calibratedCheck = new System.Windows.Forms.CheckBox( );
this.validCheck = new System.Windows.Forms.CheckBox( );
this.getInputButton = new System.Windows.Forms.Button( );
this.inputPortCombo = new System.Windows.Forms.ComboBox( );
this.groupBox1.SuspendLayout( );
this.groupBox2.SuspendLayout( );
this.groupBox3.SuspendLayout( );
this.groupBox4.SuspendLayout( );
this.groupBox5.SuspendLayout( );
( (System.ComponentModel.ISupportInitialize) ( this.turnRatioUpDown ) ).BeginInit( );
( (System.ComponentModel.ISupportInitialize) ( this.powerUpDown ) ).BeginInit( );
this.groupBox6.SuspendLayout( );
this.SuspendLayout( );
//
// groupBox1
//
this.groupBox1.Controls.Add( this.disconnectButton );
this.groupBox1.Controls.Add( this.connectButton );
this.groupBox1.Controls.Add( this.portBox );
this.groupBox1.Controls.Add( this.label1 );
this.groupBox1.Location = new System.Drawing.Point( 10, 10 );
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size( 280, 55 );
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Connection";
//
// disconnectButton
//
this.disconnectButton.Location = new System.Drawing.Point( 200, 24 );
this.disconnectButton.Name = "disconnectButton";
this.disconnectButton.Size = new System.Drawing.Size( 70, 23 );
this.disconnectButton.TabIndex = 3;
this.disconnectButton.Text = "&Disconnect";
this.disconnectButton.UseVisualStyleBackColor = true;
this.disconnectButton.Click += new System.EventHandler( this.disconnectButton_Click );
//
// connectButton
//
this.connectButton.Location = new System.Drawing.Point( 125, 24 );
this.connectButton.Name = "connectButton";
this.connectButton.Size = new System.Drawing.Size( 70, 23 );
this.connectButton.TabIndex = 2;
this.connectButton.Text = "&Connect";
this.connectButton.UseVisualStyleBackColor = true;
this.connectButton.Click += new System.EventHandler( this.connectButton_Click );
//
// portBox
//
this.portBox.Location = new System.Drawing.Point( 70, 25 );
this.portBox.Name = "portBox";
this.portBox.Size = new System.Drawing.Size( 48, 20 );
this.portBox.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point( 10, 28 );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size( 56, 13 );
this.label1.TabIndex = 0;
this.label1.Text = "COM Port:";
//
// groupBox2
//
this.groupBox2.Controls.Add( this.batteryLevelBox );
this.groupBox2.Controls.Add( this.label8 );
this.groupBox2.Controls.Add( this.freeUserFlashBox );
this.groupBox2.Controls.Add( this.label7 );
this.groupBox2.Controls.Add( this.btSignalStrengthBox );
this.groupBox2.Controls.Add( this.label6 );
this.groupBox2.Controls.Add( this.btAddressBox );
this.groupBox2.Controls.Add( this.label5 );
this.groupBox2.Controls.Add( this.deviceNameBox );
this.groupBox2.Controls.Add( this.label4 );
this.groupBox2.Controls.Add( this.protocolBox );
this.groupBox2.Controls.Add( this.label3 );
this.groupBox2.Controls.Add( this.firmwareBox );
this.groupBox2.Controls.Add( this.label2 );
this.groupBox2.Location = new System.Drawing.Point( 10, 75 );
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size( 280, 245 );
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Device info";
//
// batteryLevelBox
//
this.batteryLevelBox.Location = new System.Drawing.Point( 110, 175 );
this.batteryLevelBox.Name = "batteryLevelBox";
this.batteryLevelBox.ReadOnly = true;
this.batteryLevelBox.Size = new System.Drawing.Size( 100, 20 );
this.batteryLevelBox.TabIndex = 12;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point( 10, 178 );
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size( 68, 13 );
this.label8.TabIndex = 11;
this.label8.Text = "Battery level:";
//
// freeUserFlashBox
//
this.freeUserFlashBox.Location = new System.Drawing.Point( 110, 145 );
this.freeUserFlashBox.Name = "freeUserFlashBox";
this.freeUserFlashBox.ReadOnly = true;
this.freeUserFlashBox.Size = new System.Drawing.Size( 100, 20 );
this.freeUserFlashBox.TabIndex = 10;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point( 10, 148 );
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size( 82, 13 );
this.label7.TabIndex = 2;
this.label7.Text = "Free user Flash:";
//
// btSignalStrengthBox
//
this.btSignalStrengthBox.Location = new System.Drawing.Point( 110, 115 );
this.btSignalStrengthBox.Name = "btSignalStrengthBox";
this.btSignalStrengthBox.ReadOnly = true;
this.btSignalStrengthBox.Size = new System.Drawing.Size( 100, 20 );
this.btSignalStrengthBox.TabIndex = 9;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point( 10, 118 );
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size( 80, 13 );
this.label6.TabIndex = 8;
this.label6.Text = "Signal strength:";
//
// btAddressBox
//
this.btAddressBox.Location = new System.Drawing.Point( 110, 85 );
this.btAddressBox.Name = "btAddressBox";
this.btAddressBox.ReadOnly = true;
this.btAddressBox.Size = new System.Drawing.Size( 160, 20 );
this.btAddressBox.TabIndex = 7;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point( 10, 88 );
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size( 95, 13 );
this.label5.TabIndex = 6;
this.label5.Text = "Bluetooth address:";
//
// deviceNameBox
//
this.deviceNameBox.Location = new System.Drawing.Point( 110, 55 );
this.deviceNameBox.Name = "deviceNameBox";
this.deviceNameBox.ReadOnly = true;
this.deviceNameBox.Size = new System.Drawing.Size( 160, 20 );
this.deviceNameBox.TabIndex = 5;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point( 10, 58 );
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size( 73, 13 );
this.label4.TabIndex = 4;
this.label4.Text = "Device name:";
//
// protocolBox
//
this.protocolBox.Location = new System.Drawing.Point( 210, 25 );
this.protocolBox.Name = "protocolBox";
this.protocolBox.ReadOnly = true;
this.protocolBox.Size = new System.Drawing.Size( 60, 20 );
this.protocolBox.TabIndex = 3;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point( 155, 28 );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size( 49, 13 );
this.label3.TabIndex = 2;
this.label3.Text = "Protocol:";
//
// firmwareBox
//
this.firmwareBox.Location = new System.Drawing.Point( 70, 25 );
this.firmwareBox.Name = "firmwareBox";
this.firmwareBox.ReadOnly = true;
this.firmwareBox.Size = new System.Drawing.Size( 60, 20 );
this.firmwareBox.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point( 10, 28 );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size( 52, 13 );
this.label2.TabIndex = 0;
this.label2.Text = "Firmware:";
//
// groupBox3
//
this.groupBox3.Controls.Add( this.rotationCountBox );
this.groupBox3.Controls.Add( this.label16 );
this.groupBox3.Controls.Add( this.blockTachoCountBox );
this.groupBox3.Controls.Add( this.label15 );
this.groupBox3.Controls.Add( this.tachoCountBox );
this.groupBox3.Controls.Add( this.label14 );
this.groupBox3.Controls.Add( this.groupBox4 );
this.groupBox3.Controls.Add( this.getMotorStateButton );
this.groupBox3.Controls.Add( this.setMotorStateButton );
this.groupBox3.Controls.Add( this.resetMotorButton );
this.groupBox3.Controls.Add( this.motorCombo );
this.groupBox3.Location = new System.Drawing.Point( 300, 10 );
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size( 275, 310 );
this.groupBox3.TabIndex = 6;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Motor control";
//
// rotationCountBox
//
this.rotationCountBox.Location = new System.Drawing.Point( 110, 280 );
this.rotationCountBox.Name = "rotationCountBox";
this.rotationCountBox.ReadOnly = true;
this.rotationCountBox.Size = new System.Drawing.Size( 100, 20 );
this.rotationCountBox.TabIndex = 12;
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point( 10, 283 );
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size( 80, 13 );
this.label16.TabIndex = 11;
this.label16.Text = "Rotation count:";
this.toolTip.SetToolTip( this.label16, "Current position relative to last reset of motor\'s rotation sensor" );
//
// blockTachoCountBox
//
this.blockTachoCountBox.Location = new System.Drawing.Point( 110, 255 );
this.blockTachoCountBox.Name = "blockTachoCountBox";
this.blockTachoCountBox.ReadOnly = true;
this.blockTachoCountBox.Size = new System.Drawing.Size( 100, 20 );
this.blockTachoCountBox.TabIndex = 10;
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point( 10, 258 );
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size( 97, 13 );
this.label15.TabIndex = 9;
this.label15.Text = "Block tacho count:";
this.toolTip.SetToolTip( this.label15, "Current position relative to last programmed movement" );
//
// tachoCountBox
//
this.tachoCountBox.Location = new System.Drawing.Point( 110, 230 );
this.tachoCountBox.Name = "tachoCountBox";
this.tachoCountBox.ReadOnly = true;
this.tachoCountBox.Size = new System.Drawing.Size( 100, 20 );
this.tachoCountBox.TabIndex = 8;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point( 10, 233 );
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size( 71, 13 );
this.label14.TabIndex = 7;
this.label14.Text = "Tacho count:";
this.toolTip.SetToolTip( this.label14, "Number of counts since last reset of motor counter" );
//
// groupBox4
//
this.groupBox4.Controls.Add( this.runStateCombo );
this.groupBox4.Controls.Add( this.label13 );
this.groupBox4.Controls.Add( this.regulationModeCombo );
this.groupBox4.Controls.Add( this.label12 );
this.groupBox4.Controls.Add( this.groupBox5 );
this.groupBox4.Controls.Add( this.tachoLimitBox );
this.groupBox4.Controls.Add( this.label11 );
this.groupBox4.Controls.Add( this.turnRatioUpDown );
this.groupBox4.Controls.Add( this.label10 );
this.groupBox4.Controls.Add( this.label9 );
this.groupBox4.Controls.Add( this.powerUpDown );
this.groupBox4.Location = new System.Drawing.Point( 5, 45 );
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size( 265, 180 );
this.groupBox4.TabIndex = 6;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Motor state";
//
// runStateCombo
//
this.runStateCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.runStateCombo.FormattingEnabled = true;
this.runStateCombo.Items.AddRange( new object[] {
"Idle",
"Rump-Up",
"Running",
"Rump-Down"} );
this.runStateCombo.Location = new System.Drawing.Point( 100, 150 );
this.runStateCombo.Name = "runStateCombo";
this.runStateCombo.Size = new System.Drawing.Size( 140, 21 );
this.runStateCombo.TabIndex = 14;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point( 10, 153 );
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size( 56, 13 );
this.label13.TabIndex = 13;
this.label13.Text = "Run state:";
//
// regulationModeCombo
//
this.regulationModeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.regulationModeCombo.FormattingEnabled = true;
this.regulationModeCombo.Items.AddRange( new object[] {
"Idle",
"Speed",
"Sync"} );
this.regulationModeCombo.Location = new System.Drawing.Point( 100, 125 );
this.regulationModeCombo.Name = "regulationModeCombo";
this.regulationModeCombo.Size = new System.Drawing.Size( 140, 21 );
this.regulationModeCombo.TabIndex = 12;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point( 10, 128 );
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size( 90, 13 );
this.label12.TabIndex = 11;
this.label12.Text = "Regulation mode:";
//
// groupBox5
//
this.groupBox5.Controls.Add( this.modeRegulatedBox );
this.groupBox5.Controls.Add( this.modeBrakeCheck );
this.groupBox5.Controls.Add( this.modeOnCheck );
this.groupBox5.Location = new System.Drawing.Point( 5, 70 );
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size( 255, 45 );
this.groupBox5.TabIndex = 10;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Mode";
//
// modeRegulatedBox
//
this.modeRegulatedBox.AutoSize = true;
this.modeRegulatedBox.Location = new System.Drawing.Point( 170, 20 );
this.modeRegulatedBox.Name = "modeRegulatedBox";
this.modeRegulatedBox.Size = new System.Drawing.Size( 75, 17 );
this.modeRegulatedBox.TabIndex = 2;
this.modeRegulatedBox.Text = "Regulated";
this.modeRegulatedBox.UseVisualStyleBackColor = true;
//
// modeBrakeCheck
//
this.modeBrakeCheck.AutoSize = true;
this.modeBrakeCheck.Location = new System.Drawing.Point( 90, 20 );
this.modeBrakeCheck.Name = "modeBrakeCheck";
this.modeBrakeCheck.Size = new System.Drawing.Size( 54, 17 );
this.modeBrakeCheck.TabIndex = 1;
this.modeBrakeCheck.Text = "Brake";
this.modeBrakeCheck.UseVisualStyleBackColor = true;
//
// modeOnCheck
//
this.modeOnCheck.AutoSize = true;
this.modeOnCheck.Checked = true;
this.modeOnCheck.CheckState = System.Windows.Forms.CheckState.Checked;
this.modeOnCheck.Location = new System.Drawing.Point( 10, 20 );
this.modeOnCheck.Name = "modeOnCheck";
this.modeOnCheck.Size = new System.Drawing.Size( 40, 17 );
this.modeOnCheck.TabIndex = 0;
this.modeOnCheck.Text = "On";
this.modeOnCheck.UseVisualStyleBackColor = true;
//
// tachoLimitBox
//
this.tachoLimitBox.Location = new System.Drawing.Point( 140, 45 );
this.tachoLimitBox.Name = "tachoLimitBox";
this.tachoLimitBox.Size = new System.Drawing.Size( 100, 20 );
this.tachoLimitBox.TabIndex = 9;
this.tachoLimitBox.Text = "1000";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point( 10, 48 );
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size( 130, 13 );
this.label11.TabIndex = 8;
this.label11.Text = "Tacho limit (0 run forever):";
//
// turnRatioUpDown
//
this.turnRatioUpDown.Location = new System.Drawing.Point( 180, 20 );
this.turnRatioUpDown.Minimum = new decimal( new int[] {
100,
0,
0,
-2147483648} );
this.turnRatioUpDown.Name = "turnRatioUpDown";
this.turnRatioUpDown.Size = new System.Drawing.Size( 60, 20 );
this.turnRatioUpDown.TabIndex = 7;
this.turnRatioUpDown.Value = new decimal( new int[] {
50,
0,
0,
0} );
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point( 125, 23 );
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size( 55, 13 );
this.label10.TabIndex = 6;
this.label10.Text = "Turn ratio:";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point( 10, 23 );
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size( 40, 13 );
this.label9.TabIndex = 4;
this.label9.Text = "Power:";
//
// powerUpDown
//
this.powerUpDown.Location = new System.Drawing.Point( 50, 20 );
this.powerUpDown.Minimum = new decimal( new int[] {
100,
0,
0,
-2147483648} );
this.powerUpDown.Name = "powerUpDown";
this.powerUpDown.Size = new System.Drawing.Size( 60, 20 );
this.powerUpDown.TabIndex = 5;
this.powerUpDown.Value = new decimal( new int[] {
70,
0,
0,
0} );
//
// getMotorStateButton
//
this.getMotorStateButton.Enabled = false;
this.getMotorStateButton.Location = new System.Drawing.Point( 210, 19 );
this.getMotorStateButton.Name = "getMotorStateButton";
this.getMotorStateButton.Size = new System.Drawing.Size( 60, 23 );
this.getMotorStateButton.TabIndex = 3;
this.getMotorStateButton.Text = "&Get state";
this.getMotorStateButton.UseVisualStyleBackColor = true;
this.getMotorStateButton.Click += new System.EventHandler( this.getMotorStateButton_Click );
//
// setMotorStateButton
//
this.setMotorStateButton.Enabled = false;
this.setMotorStateButton.Location = new System.Drawing.Point( 145, 19 );
this.setMotorStateButton.Name = "setMotorStateButton";
this.setMotorStateButton.Size = new System.Drawing.Size( 60, 23 );
this.setMotorStateButton.TabIndex = 2;
this.setMotorStateButton.Text = "&Set state";
this.setMotorStateButton.UseVisualStyleBackColor = true;
this.setMotorStateButton.Click += new System.EventHandler( this.setMotorStateButton_Click );
//
// resetMotorButton
//
this.resetMotorButton.Enabled = false;
this.resetMotorButton.Location = new System.Drawing.Point( 80, 19 );
this.resetMotorButton.Name = "resetMotorButton";
this.resetMotorButton.Size = new System.Drawing.Size( 60, 23 );
this.resetMotorButton.TabIndex = 1;
this.resetMotorButton.Text = "&Reset";
this.resetMotorButton.UseVisualStyleBackColor = true;
this.resetMotorButton.Click += new System.EventHandler( this.resetMotorButton_Click );
//
// motorCombo
//
this.motorCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.motorCombo.FormattingEnabled = true;
this.motorCombo.Items.AddRange( new object[] {
"Motor A",
"Motor B",
"Motor C"} );
this.motorCombo.Location = new System.Drawing.Point( 10, 20 );
this.motorCombo.Name = "motorCombo";
this.motorCombo.Size = new System.Drawing.Size( 65, 21 );
this.motorCombo.TabIndex = 0;
//
// toolTip
//
this.toolTip.BackColor = System.Drawing.Color.FromArgb( ( (int) ( ( (byte) ( 192 ) ) ) ), ( (int) ( ( (byte) ( 255 ) ) ) ), ( (int) ( ( (byte) ( 192 ) ) ) ) );
//
// groupBox6
//
this.groupBox6.Controls.Add( this.setInputModeButton );
this.groupBox6.Controls.Add( this.sensorModeCombo );
this.groupBox6.Controls.Add( this.label25 );
this.groupBox6.Controls.Add( this.sensorTypeCombo );
this.groupBox6.Controls.Add( this.label23 );
this.groupBox6.Controls.Add( this.label24 );
this.groupBox6.Controls.Add( this.calibratedInputBox );
this.groupBox6.Controls.Add( this.label22 );
this.groupBox6.Controls.Add( this.scaledInputBox );
this.groupBox6.Controls.Add( this.label21 );
this.groupBox6.Controls.Add( this.normalizedInputBox );
this.groupBox6.Controls.Add( this.label20 );
this.groupBox6.Controls.Add( this.rawInputBox );
this.groupBox6.Controls.Add( this.label19 );
this.groupBox6.Controls.Add( this.sensorModeBox );
this.groupBox6.Controls.Add( this.label18 );
this.groupBox6.Controls.Add( this.sensorTypeBox );
this.groupBox6.Controls.Add( this.label17 );
this.groupBox6.Controls.Add( this.calibratedCheck );
this.groupBox6.Controls.Add( this.validCheck );
this.groupBox6.Controls.Add( this.getInputButton );
this.groupBox6.Controls.Add( this.inputPortCombo );
this.groupBox6.Location = new System.Drawing.Point( 585, 10 );
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size( 170, 310 );
this.groupBox6.TabIndex = 8;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Input ports";
//
// setInputModeButton
//
this.setInputModeButton.Enabled = false;
this.setInputModeButton.Location = new System.Drawing.Point( 80, 283 );
this.setInputModeButton.Name = "setInputModeButton";
this.setInputModeButton.Size = new System.Drawing.Size( 80, 23 );
this.setInputModeButton.TabIndex = 21;
this.setInputModeButton.Text = "Set &mode";
this.setInputModeButton.UseVisualStyleBackColor = true;
this.setInputModeButton.Click += new System.EventHandler( this.setInputModeButton_Click );
//
// sensorModeCombo
//
this.sensorModeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.sensorModeCombo.FormattingEnabled = true;
this.sensorModeCombo.Items.AddRange( new object[] {
"Raw",
"Boolean",
"Transition Counter",
"Periodic Counter",
"PCT Full Scale",
"Celsius",
"Fahrenheit",
"Angle Steps"} );
this.sensorModeCombo.Location = new System.Drawing.Point( 80, 260 );
this.sensorModeCombo.Name = "sensorModeCombo";
this.sensorModeCombo.Size = new System.Drawing.Size( 80, 21 );
this.sensorModeCombo.TabIndex = 20;
//
// label25
//
this.label25.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.label25.Location = new System.Drawing.Point( 10, 227 );
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size( 150, 2 );
this.label25.TabIndex = 19;
//
// sensorTypeCombo
//
this.sensorTypeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.sensorTypeCombo.FormattingEnabled = true;
this.sensorTypeCombo.Items.AddRange( new object[] {
"No Sensor",
"Switch",
"Temperature",
"Reflection",
"Angle",
"Light Active",
"Light Inactive",
"Sound (dB)",
"Sound (dBA)",
"Custom",
"Lowspeed",
"Lowspeed 9V"} );
this.sensorTypeCombo.Location = new System.Drawing.Point( 80, 235 );
this.sensorTypeCombo.Name = "sensorTypeCombo";
this.sensorTypeCombo.Size = new System.Drawing.Size( 80, 21 );
this.sensorTypeCombo.TabIndex = 18;
//
// label23
//
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point( 10, 263 );
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size( 72, 13 );
this.label23.TabIndex = 17;
this.label23.Text = "Sensor mode:";
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point( 10, 238 );
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size( 66, 13 );
this.label24.TabIndex = 16;
this.label24.Text = "Sensor type:";
//
// calibratedInputBox
//
this.calibratedInputBox.Location = new System.Drawing.Point( 80, 200 );
this.calibratedInputBox.Name = "calibratedInputBox";
this.calibratedInputBox.ReadOnly = true;
this.calibratedInputBox.Size = new System.Drawing.Size( 80, 20 );
this.calibratedInputBox.TabIndex = 15;
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point( 10, 203 );
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size( 57, 13 );
this.label22.TabIndex = 14;
this.label22.Text = "Calibrated:";
//
// scaledInputBox
//
this.scaledInputBox.Location = new System.Drawing.Point( 80, 175 );
this.scaledInputBox.Name = "scaledInputBox";
this.scaledInputBox.ReadOnly = true;
this.scaledInputBox.Size = new System.Drawing.Size( 80, 20 );
this.scaledInputBox.TabIndex = 13;
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point( 10, 178 );
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size( 43, 13 );
this.label21.TabIndex = 12;
this.label21.Text = "Scaled:";
//
// normalizedInputBox
//
this.normalizedInputBox.Location = new System.Drawing.Point( 80, 150 );
this.normalizedInputBox.Name = "normalizedInputBox";
this.normalizedInputBox.ReadOnly = true;
this.normalizedInputBox.Size = new System.Drawing.Size( 80, 20 );
this.normalizedInputBox.TabIndex = 11;
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point( 10, 153 );
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size( 62, 13 );
this.label20.TabIndex = 10;
this.label20.Text = "Normalized:";
//
// rawInputBox
//
this.rawInputBox.Location = new System.Drawing.Point( 80, 125 );
this.rawInputBox.Name = "rawInputBox";
this.rawInputBox.ReadOnly = true;
this.rawInputBox.Size = new System.Drawing.Size( 80, 20 );
this.rawInputBox.TabIndex = 9;
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point( 10, 128 );
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size( 32, 13 );
this.label19.TabIndex = 8;
this.label19.Text = "Row:";
//
// sensorModeBox
//
this.sensorModeBox.Location = new System.Drawing.Point( 80, 100 );
this.sensorModeBox.Name = "sensorModeBox";
this.sensorModeBox.ReadOnly = true;
this.sensorModeBox.Size = new System.Drawing.Size( 80, 20 );
this.sensorModeBox.TabIndex = 7;
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point( 10, 103 );
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size( 72, 13 );
this.label18.TabIndex = 6;
this.label18.Text = "Sensor mode:";
//
// sensorTypeBox
//
this.sensorTypeBox.Location = new System.Drawing.Point( 80, 75 );
this.sensorTypeBox.Name = "sensorTypeBox";
this.sensorTypeBox.ReadOnly = true;
this.sensorTypeBox.Size = new System.Drawing.Size( 80, 20 );
this.sensorTypeBox.TabIndex = 5;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point( 10, 78 );
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size( 66, 13 );
this.label17.TabIndex = 4;
this.label17.Text = "Sensor type:";
//
// calibratedCheck
//
this.calibratedCheck.AutoSize = true;
this.calibratedCheck.Enabled = false;
this.calibratedCheck.Location = new System.Drawing.Point( 80, 50 );
this.calibratedCheck.Name = "calibratedCheck";
this.calibratedCheck.Size = new System.Drawing.Size( 84, 17 );
this.calibratedCheck.TabIndex = 3;
this.calibratedCheck.Text = "Is Calibrated";
this.calibratedCheck.UseVisualStyleBackColor = true;
//
// validCheck
//
this.validCheck.AutoSize = true;
this.validCheck.Enabled = false;
this.validCheck.Location = new System.Drawing.Point( 10, 50 );
this.validCheck.Name = "validCheck";
this.validCheck.Size = new System.Drawing.Size( 60, 17 );
this.validCheck.TabIndex = 2;
this.validCheck.Text = "Is Valid";
this.validCheck.UseVisualStyleBackColor = true;
//
// getInputButton
//
this.getInputButton.Enabled = false;
this.getInputButton.Location = new System.Drawing.Point( 95, 19 );
this.getInputButton.Name = "getInputButton";
this.getInputButton.Size = new System.Drawing.Size( 65, 23 );
this.getInputButton.TabIndex = 1;
this.getInputButton.Text = "Get &input";
this.getInputButton.UseVisualStyleBackColor = true;
this.getInputButton.Click += new System.EventHandler( this.getInputButton_Click );
//
// inputPortCombo
//
this.inputPortCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.inputPortCombo.FormattingEnabled = true;
this.inputPortCombo.Items.AddRange( new object[] {
"Port 1",
"Port 2",
"Port 3",
"Port 4"} );
this.inputPortCombo.Location = new System.Drawing.Point( 10, 20 );
this.inputPortCombo.Name = "inputPortCombo";
this.inputPortCombo.Size = new System.Drawing.Size( 75, 21 );
this.inputPortCombo.TabIndex = 0;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 772, 329 );
this.Controls.Add( this.groupBox6 );
this.Controls.Add( this.groupBox3 );
this.Controls.Add( this.groupBox2 );
this.Controls.Add( this.groupBox1 );
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "MainForm";
this.ShowIcon = false;
this.Text = "Lego NXT Test";
this.groupBox1.ResumeLayout( false );
this.groupBox1.PerformLayout( );
this.groupBox2.ResumeLayout( false );
this.groupBox2.PerformLayout( );
this.groupBox3.ResumeLayout( false );
this.groupBox3.PerformLayout( );
this.groupBox4.ResumeLayout( false );
this.groupBox4.PerformLayout( );
this.groupBox5.ResumeLayout( false );
this.groupBox5.PerformLayout( );
( (System.ComponentModel.ISupportInitialize) ( this.turnRatioUpDown ) ).EndInit( );
( (System.ComponentModel.ISupportInitialize) ( this.powerUpDown ) ).EndInit( );
this.groupBox6.ResumeLayout( false );
this.groupBox6.PerformLayout( );
this.ResumeLayout( false );
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox portBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button connectButton;
private System.Windows.Forms.Button disconnectButton;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox protocolBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox firmwareBox;
private System.Windows.Forms.TextBox deviceNameBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox freeUserFlashBox;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox btSignalStrengthBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox btAddressBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox batteryLevelBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.ComboBox motorCombo;
private System.Windows.Forms.Button getMotorStateButton;
private System.Windows.Forms.Button setMotorStateButton;
private System.Windows.Forms.Button resetMotorButton;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.NumericUpDown powerUpDown;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.NumericUpDown turnRatioUpDown;
private System.Windows.Forms.TextBox tachoLimitBox;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.CheckBox modeOnCheck;
private System.Windows.Forms.CheckBox modeRegulatedBox;
private System.Windows.Forms.CheckBox modeBrakeCheck;
private System.Windows.Forms.ComboBox regulationModeCombo;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.ComboBox runStateCombo;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.TextBox tachoCountBox;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.TextBox blockTachoCountBox;
private System.Windows.Forms.TextBox rotationCountBox;
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.ComboBox inputPortCombo;
private System.Windows.Forms.Button getInputButton;
private System.Windows.Forms.CheckBox calibratedCheck;
private System.Windows.Forms.CheckBox validCheck;
private System.Windows.Forms.TextBox sensorModeBox;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.TextBox sensorTypeBox;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TextBox rawInputBox;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.TextBox normalizedInputBox;
private System.Windows.Forms.TextBox calibratedInputBox;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.TextBox scaledInputBox;
private System.Windows.Forms.ComboBox sensorTypeCombo;
private System.Windows.Forms.Label label23;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.ComboBox sensorModeCombo;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.Button setInputModeButton;
}
}
| |
using J2N.IO;
using J2N.IO.MemoryMappedFiles;
using J2N.Numerics;
using Lucene.Net.Diagnostics;
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace Lucene.Net.Store
{
/*
* 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 Constants = Lucene.Net.Util.Constants;
/// <summary>
/// File-based <see cref="Directory"/> implementation that uses
/// <see cref="MemoryMappedFile"/> for reading, and
/// <see cref="FSDirectory.FSIndexOutput"/> for writing.
///
/// <para/><b>NOTE</b>: memory mapping uses up a portion of the
/// virtual memory address space in your process equal to the
/// size of the file being mapped. Before using this class,
/// be sure your have plenty of virtual address space, e.g. by
/// using a 64 bit runtime, or a 32 bit runtime with indexes that are
/// guaranteed to fit within the address space.
/// On 32 bit platforms also consult <see cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
/// if you have problems with mmap failing because of fragmented
/// address space. If you get an <see cref="OutOfMemoryException"/>, it is recommended
/// to reduce the chunk size, until it works.
/// <para>
/// <b>NOTE:</b> Accessing this class either directly or
/// indirectly from a thread while it's interrupted can close the
/// underlying channel immediately if at the same time the thread is
/// blocked on IO. The channel will remain closed and subsequent access
/// to <see cref="MMapDirectory"/> will throw a <see cref="ObjectDisposedException"/>.
/// </para>
/// </summary>
public class MMapDirectory : FSDirectory
{
// LUCENENET specific - unmap hack not needed
/// <summary>
/// Default max chunk size. </summary>
/// <seealso cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
public static readonly int DEFAULT_MAX_BUFF = Constants.RUNTIME_IS_64BIT ? (1 << 30) : (1 << 28);
private readonly int chunkSizePower;
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or null for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path, LockFactory lockFactory)
: this(path, lockFactory, DEFAULT_MAX_BUFF)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path)
: this(path, null)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location, specifying the
/// maximum chunk size used for memory mapping.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or <c>null</c> for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <param name="maxChunkSize"> maximum chunk size (default is 1 GiBytes for
/// 64 bit runtimes and 256 MiBytes for 32 bit runtimes) used for memory mapping.
/// <para/>
/// Especially on 32 bit platform, the address space can be very fragmented,
/// so large index files cannot be mapped. Using a lower chunk size makes
/// the directory implementation a little bit slower (as the correct chunk
/// may be resolved on lots of seeks) but the chance is higher that mmap
/// does not fail. On 64 bit platforms, this parameter should always
/// be <c>1 << 30</c>, as the address space is big enough.
/// <para/>
/// <b>Please note:</b> The chunk size is always rounded down to a power of 2.
/// </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path, LockFactory lockFactory, int maxChunkSize)
: base(path, lockFactory)
{
if (maxChunkSize <= 0)
{
throw new ArgumentException("Maximum chunk size for mmap must be >0");
}
this.chunkSizePower = 31 - maxChunkSize.LeadingZeroCount();
if (Debugging.AssertsEnabled) Debugging.Assert(this.chunkSizePower >= 0 && this.chunkSizePower <= 30);
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or null for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path, LockFactory lockFactory)
: this(path, lockFactory, DEFAULT_MAX_BUFF)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path)
: this(path, null)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location, specifying the
/// maximum chunk size used for memory mapping.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or <c>null</c> for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <param name="maxChunkSize"> maximum chunk size (default is 1 GiBytes for
/// 64 bit runtimes and 256 MiBytes for 32 bit runtimes) used for memory mapping.
/// <para/>
/// Especially on 32 bit platform, the address space can be very fragmented,
/// so large index files cannot be mapped. Using a lower chunk size makes
/// the directory implementation a little bit slower (as the correct chunk
/// may be resolved on lots of seeks) but the chance is higher that mmap
/// does not fail. On 64 bit platforms, this parameter should always
/// be <c>1 << 30</c>, as the address space is big enough.
/// <para/>
/// <b>Please note:</b> The chunk size is always rounded down to a power of 2.
/// </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path, LockFactory lockFactory, int maxChunkSize)
: this(new DirectoryInfo(path), lockFactory, maxChunkSize)
{
}
// LUCENENET specific - Some JREs had a bug that didn't allow them to unmap.
// But according to MSDN, the MemoryMappedFile.Dispose() method will
// indeed "release all resources". Therefore unmap hack is not needed in .NET.
/// <summary>
/// Returns the current mmap chunk size. </summary>
/// <seealso cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
public int MaxChunkSize => 1 << chunkSizePower;
/// <summary>
/// Creates an <see cref="IndexInput"/> for the file with the given name. </summary>
public override IndexInput OpenInput(string name, IOContext context)
{
EnsureOpen();
var file = new FileInfo(Path.Combine(Directory.FullName, name));
var fc = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return new MMapIndexInput(this, "MMapIndexInput(path=\"" + file + "\")", fc);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
var full = (MMapIndexInput)OpenInput(name, context);
return new IndexInputSlicerAnonymousInnerClassHelper(this, full);
}
private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer
{
private readonly MMapDirectory outerInstance;
private MMapIndexInput full;
public IndexInputSlicerAnonymousInnerClassHelper(MMapDirectory outerInstance, MMapIndexInput full)
{
this.outerInstance = outerInstance;
this.full = full;
}
public override IndexInput OpenSlice(string sliceDescription, long offset, long length)
{
outerInstance.EnsureOpen();
return full.Slice(sliceDescription, offset, length);
}
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public override IndexInput OpenFullSlice()
{
outerInstance.EnsureOpen();
return (IndexInput)full.Clone();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
full.Dispose();
}
}
}
public sealed class MMapIndexInput : ByteBufferIndexInput
{
internal MemoryMappedFile memoryMappedFile; // .NET port: this is equivalent to FileChannel.map
private readonly FileStream fc;
private readonly MMapDirectory outerInstance;
internal MMapIndexInput(MMapDirectory outerInstance, string resourceDescription, FileStream fc)
: base(resourceDescription, null, fc.Length, outerInstance.chunkSizePower, true)
{
this.outerInstance = outerInstance;
this.fc = fc ?? throw new ArgumentNullException("fc");
this.SetBuffers(outerInstance.Map(this, fc, 0, fc.Length));
}
protected override sealed void Dispose(bool disposing)
{
try
{
if (disposing)
{
try
{
if (this.memoryMappedFile != null)
{
this.memoryMappedFile.Dispose();
this.memoryMappedFile = null;
}
}
finally
{
// LUCENENET: If the file is 0 length we will not create a memoryMappedFile above
// so we must always ensure the FileStream is explicitly disposed.
this.fc.Dispose();
}
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Try to unmap the buffer, this method silently fails if no support
/// for that in the runtime. On Windows, this leads to the fact,
/// that mmapped files cannot be modified or deleted.
/// </summary>
protected override void FreeBuffer(ByteBuffer buffer)
{
// LUCENENET specific: this should free the memory mapped view accessor
if (buffer is IDisposable disposable)
disposable.Dispose();
// LUCENENET specific: no need for UnmapHack
}
}
/// <summary>
/// Maps a file into a set of buffers </summary>
internal virtual ByteBuffer[] Map(MMapIndexInput input, FileStream fc, long offset, long length)
{
if (length.TripleShift(chunkSizePower) >= int.MaxValue)
throw new ArgumentException("RandomAccessFile too big for chunk size: " + fc.ToString());
// LUCENENET specific: Return empty buffer if length is 0, rather than attempting to create a MemoryMappedFile.
// Part of a solution provided by Vincent Van Den Berghe: http://apache.markmail.org/message/hafnuhq2ydhfjmi2
if (length == 0)
{
return new[] { ByteBuffer.Allocate(0).AsReadOnlyBuffer() };
}
long chunkSize = 1L << chunkSizePower;
// we always allocate one more buffer, the last one may be a 0 byte one
int nrBuffers = (int)((long)((ulong)length >> chunkSizePower)) + 1;
ByteBuffer[] buffers = new ByteBuffer[nrBuffers];
if (input.memoryMappedFile == null)
{
input.memoryMappedFile = MemoryMappedFile.CreateFromFile(
fileStream: fc,
mapName: null,
capacity: length,
access: MemoryMappedFileAccess.Read,
#if FEATURE_MEMORYMAPPEDFILESECURITY
memoryMappedFileSecurity: null,
#endif
inheritability: HandleInheritability.Inheritable,
leaveOpen: true); // LUCENENET: We explicitly dispose the FileStream separately.
}
long bufferStart = 0L;
for (int bufNr = 0; bufNr < nrBuffers; bufNr++)
{
int bufSize = (int)((length > (bufferStart + chunkSize)) ? chunkSize : (length - bufferStart));
// LUCENENET: We get an UnauthorizedAccessException if we create a 0 byte file at the end of the range.
// See: https://stackoverflow.com/a/5501331
// We can fix this by moving back 1 byte on the offset if the bufSize is 0.
int adjust = 0;
if (bufSize == 0 && bufNr == (nrBuffers - 1) && (offset + bufferStart) > 0)
{
adjust = 1;
}
buffers[bufNr] = input.memoryMappedFile.CreateViewByteBuffer(
offset: (offset + bufferStart) - adjust,
size: bufSize,
access: MemoryMappedFileAccess.Read);
bufferStart += bufSize;
}
return buffers;
}
}
}
| |
namespace YGZ.HuiBird.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
UserName = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailAddress = c.String(nullable: false, maxLength: 256),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 128),
PasswordResetCode = c.String(maxLength: 128),
LastLoginTime = c.DateTime(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
}
public override void Down()
{
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpSettings", new[] { "TenantId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpUsers", new[] { "TenantId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "TenantId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings");
DropTable("dbo.AbpUserRoles");
DropTable("dbo.AbpUserLogins");
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
using EasyNetQ.Consumer;
using EasyNetQ.Internals;
using EasyNetQ.Topology;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace EasyNetQ;
/// <summary>
/// Various extensions for <see cref="IAdvancedBus"/>
/// </summary>
public static class AdvancedBusExtensions
{
/// <summary>
/// Consume a stream of messages
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus, Queue queue, Action<IMessage<T>, MessageReceivedInfo> handler
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, handler, _ => { });
}
/// <summary>
/// Consume a stream of messages
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)</param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus,
Queue queue,
Action<IMessage<T>, MessageReceivedInfo> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
var handlerAsync = TaskHelpers.FromAction<IMessage<T>, MessageReceivedInfo>((m, i, _) => handler(m, i));
return bus.Consume(queue, handlerAsync, configure);
}
/// <summary>
/// Consume a stream of messages asynchronously
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus, Queue queue, Func<IMessage<T>, MessageReceivedInfo, Task> handler
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, handler, _ => { });
}
/// <summary>
/// Consume a stream of messages asynchronously
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus,
Queue queue,
Func<IMessage<T>, MessageReceivedInfo, Task> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume<T>(queue, (m, i, _) => handler(m, i), configure);
}
/// <summary>
/// Consume a stream of messages asynchronously
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus,
Queue queue,
Func<IMessage<T>, MessageReceivedInfo, CancellationToken, Task> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume<T>(queue, async (m, i, c) =>
{
await handler(m, i, c).ConfigureAwait(false);
return AckStrategies.Ack;
}, configure);
}
/// <summary>
/// Consume a stream of messages asynchronously
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="handler">The message handler</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume<T>(
this IAdvancedBus bus,
Queue queue,
IMessageHandler<T> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
var consumeConfiguration = new SimpleConsumeConfiguration();
configure(consumeConfiguration);
return bus.Consume(c =>
{
if (consumeConfiguration.PrefetchCount.HasValue)
c.WithPrefetchCount(consumeConfiguration.PrefetchCount.Value);
c.ForQueue(
queue,
handler,
p =>
{
if (consumeConfiguration.ConsumerTag != null)
p.WithConsumerTag(consumeConfiguration.ConsumerTag);
if (consumeConfiguration.IsExclusive.HasValue)
p.WithExclusive(consumeConfiguration.IsExclusive.Value);
if (consumeConfiguration.Arguments != null)
p.WithArguments(consumeConfiguration.Arguments);
}
);
});
}
/// <summary>
/// Consume a stream of messages. Dispatch them to the given handlers
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers to the consumer</param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(this IAdvancedBus bus, Queue queue, Action<IHandlerRegistration> addHandlers)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, addHandlers, _ => { });
}
/// <summary>
/// Consume a stream of messages. Dispatch them to the given handlers
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers to the consumer</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Action<IHandlerRegistration> addHandlers,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
var consumeConfiguration = new SimpleConsumeConfiguration();
configure(consumeConfiguration);
return bus.Consume(c =>
{
if (consumeConfiguration.PrefetchCount.HasValue)
c.WithPrefetchCount(consumeConfiguration.PrefetchCount.Value);
c.ForQueue(
queue,
addHandlers,
p =>
{
if (consumeConfiguration.ConsumerTag != null)
p.WithConsumerTag(consumeConfiguration.ConsumerTag);
if (consumeConfiguration.IsExclusive.HasValue)
p.WithExclusive(consumeConfiguration.IsExclusive.Value);
if (consumeConfiguration.Arguments != null)
p.WithArguments(consumeConfiguration.Arguments);
}
);
});
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context.
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus, Queue queue, Action<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo> handler
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, handler, _ => { });
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Action<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
var handlerAsync = TaskHelpers.FromAction<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo>((m, p, i, _) => handler(m, p, i));
return bus.Consume(queue, handlerAsync, configure);
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Func<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo, Task> handler
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, handler, _ => { });
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Func<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo, Task<AckStrategy>> handler
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, handler, _ => { });
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Func<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo, Task> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, (m, p, i, _) => handler(m, p, i), configure);
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Func<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo, Task<AckStrategy>> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, (m, p, i, _) => handler(m, p, i), configure);
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
Func<ReadOnlyMemory<byte>, MessageProperties, MessageReceivedInfo, CancellationToken, Task> handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.Consume(queue, async (m, p, i, c) =>
{
await handler(m, p, i, c).ConfigureAwait(false);
return AckStrategies.Ack;
}, configure);
}
/// <summary>
/// Consume raw bytes from the queue.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to subscribe to</param>
/// <param name="handler">
/// The message handler. Takes the message body, message properties and some information about the
/// receive context. Returns a Task.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithPriority(10)
/// </param>
/// <returns>A disposable to cancel the consumer</returns>
public static IDisposable Consume(
this IAdvancedBus bus,
Queue queue,
MessageHandler handler,
Action<ISimpleConsumeConfiguration> configure
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
var consumeConfiguration = new SimpleConsumeConfiguration();
configure(consumeConfiguration);
return bus.Consume(c =>
{
if (consumeConfiguration.PrefetchCount.HasValue)
c.WithPrefetchCount(consumeConfiguration.PrefetchCount.Value);
c.ForQueue(
queue,
handler,
p =>
{
if (consumeConfiguration.AutoAck)
p.WithAutoAck();
if (consumeConfiguration.ConsumerTag != null)
p.WithConsumerTag(consumeConfiguration.ConsumerTag);
if (consumeConfiguration.IsExclusive.HasValue)
p.WithExclusive(consumeConfiguration.IsExclusive.Value);
if (consumeConfiguration.Arguments != null)
p.WithArguments(consumeConfiguration.Arguments);
}
);
});
}
/// <summary>
/// Publish a message as a byte array
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="exchange">The exchange to publish to</param>
/// <param name="routingKey">
/// The routing key for the message. The routing key is used for routing messages depending on the
/// exchange configuration.
/// </param>
/// <param name="mandatory">
/// This flag tells the server how to react if the message cannot be routed to a queue.
/// If this flag is true, the server will return an unroutable message with a Return method.
/// If this flag is false, the server silently drops the message.
/// </param>
/// <param name="messageProperties">The message properties</param>
/// <param name="body">The message body</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void Publish(
this IAdvancedBus bus,
Exchange exchange,
string routingKey,
bool mandatory,
MessageProperties messageProperties,
ReadOnlyMemory<byte> body,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.PublishAsync(exchange, routingKey, mandatory, messageProperties, body, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Publish a message as a .NET type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bus">The bus instance</param>
/// <param name="exchange">The exchange to publish to</param>
/// <param name="routingKey">
/// The routing key for the message. The routing key is used for routing messages depending on the
/// exchange configuration.
/// </param>
/// <param name="mandatory">
/// This flag tells the server how to react if the message cannot be routed to a queue.
/// If this flag is true, the server will return an unroutable message with a Return method.
/// If this flag is false, the server silently drops the message.
/// </param>
/// <param name="message">The message to publish</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void Publish<T>(
this IAdvancedBus bus,
Exchange exchange,
string routingKey,
bool mandatory,
IMessage<T> message,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.PublishAsync(exchange, routingKey, mandatory, message, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets stats for the given queue
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The stats of the queue</returns>
public static QueueStats GetQueueStats(
this IAdvancedBus bus, Queue queue, CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.GetQueueStatsAsync(queue, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare a transient server named queue. Note, this queue will only last for duration of the
/// connection. If there is a connection outage, EasyNetQ will not attempt to recreate
/// consumers.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The queue</returns>
public static Queue QueueDeclare(this IAdvancedBus bus, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare a queue. If the queue already exists this method does nothing
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The name of the queue</param>
/// <param name="configure">Delegate to configure the queue</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>
/// The queue
/// </returns>
public static Queue QueueDeclare(
this IAdvancedBus bus,
string name,
Action<IQueueDeclareConfiguration> configure,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(name, configure, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare a queue. If the queue already exists this method does nothing
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The name of the queue</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>
/// The queue
/// </returns>
public static Task<Queue> QueueDeclareAsync(
this IAdvancedBus bus,
string name,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(name, _ => { }, cancellationToken);
}
/// <summary>
/// Declare a queue. If the queue already exists this method does nothing
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The name of the queue</param>
/// <param name="durable">Durable queues remain active when a server restarts.</param>
/// <param name="exclusive">Exclusive queues may only be accessed by the current connection, and are deleted when that connection closes.</param>
/// <param name="autoDelete">If set, the queue is deleted when all consumers have finished using it.</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>
/// The queue
/// </returns>
public static Task<Queue> QueueDeclareAsync(
this IAdvancedBus bus,
string name,
bool durable,
bool exclusive,
bool autoDelete,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(
name,
c => c.AsDurable(durable)
.AsExclusive(exclusive)
.AsAutoDelete(autoDelete),
cancellationToken
);
}
/// <summary>
/// Declare a queue. If the queue already exists this method does nothing
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The name of the queue</param>
/// <param name="durable">Durable queues remain active when a server restarts.</param>
/// <param name="exclusive">Exclusive queues may only be accessed by the current connection, and are deleted when that connection closes.</param>
/// <param name="autoDelete">If set, the queue is deleted when all consumers have finished using it.</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>
/// The queue
/// </returns>
public static Queue QueueDeclare(
this IAdvancedBus bus,
string name,
bool durable,
bool exclusive,
bool autoDelete,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(name, durable, exclusive, autoDelete, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare a queue. If the queue already exists this method does nothing
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The name of the queue</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>
/// The queue
/// </returns>
public static Queue QueueDeclare(
this IAdvancedBus bus,
string name,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.QueueDeclareAsync(name, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare a queue passively. Throw an exception rather than create the queue if it doesn't exist
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The queue to declare</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void QueueDeclarePassive(
this IAdvancedBus bus,
string name,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.QueueDeclarePassiveAsync(name, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Bind two exchanges. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="source">The exchange</param>
/// <param name="queue">The queue</param>
/// <param name="routingKey">The routing key</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Task<Binding<Queue>> BindAsync(
this IAdvancedBus bus,
Exchange source,
Queue queue,
string routingKey,
CancellationToken cancellationToken
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(source, queue, routingKey, null, cancellationToken);
}
/// <summary>
/// Bind two exchanges. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="source">The source exchange</param>
/// <param name="destination">The destination exchange</param>
/// <param name="routingKey">The routing key</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Task<Binding<Exchange>> BindAsync(
this IAdvancedBus bus,
Exchange source,
Exchange destination,
string routingKey,
CancellationToken cancellationToken
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(source, destination, routingKey, null, cancellationToken);
}
/// <summary>
/// Bind two exchanges. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="source">The source exchange</param>
/// <param name="destination">The destination exchange</param>
/// <param name="routingKey">The routing key</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Binding<Exchange> Bind(this IAdvancedBus bus, Exchange source, Exchange destination, string routingKey, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(source, destination, routingKey, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Bind two exchanges. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="source">The source exchange</param>
/// <param name="destination">The destination exchange</param>
/// <param name="routingKey">The routing key</param>
/// <param name="arguments">The arguments</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Binding<Exchange> Bind(
this IAdvancedBus bus,
Exchange source,
Exchange destination,
string routingKey,
IDictionary<string, object> arguments,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(source, destination, routingKey, arguments, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Bind an exchange to a queue. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="exchange">The exchange to bind</param>
/// <param name="queue">The queue to bind</param>
/// <param name="routingKey">The routing key</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Binding<Queue> Bind(this IAdvancedBus bus, Exchange exchange, Queue queue, string routingKey, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(exchange, queue, routingKey, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Bind an exchange to a queue. Does nothing if the binding already exists.
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="exchange">The exchange to bind</param>
/// <param name="queue">The queue to bind</param>
/// <param name="routingKey">The routing key</param>
/// <param name="arguments">The arguments</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>A binding</returns>
public static Binding<Queue> Bind(
this IAdvancedBus bus,
Exchange exchange,
Queue queue,
string routingKey,
IDictionary<string, object> arguments,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.BindAsync(exchange, queue, routingKey, arguments, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare an exchange
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The exchange name</param>
/// <param name="type">The type of exchange</param>
/// <param name="durable">Durable exchanges remain active when a server restarts.</param>
/// <param name="autoDelete">If set, the exchange is deleted when all queues have finished using it.</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The exchange</returns>
public static Task<Exchange> ExchangeDeclareAsync(
this IAdvancedBus bus,
string name,
string type,
bool durable = true,
bool autoDelete = false,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.ExchangeDeclareAsync(name, c => c.AsDurable(durable).AsAutoDelete(autoDelete).WithType(type), cancellationToken);
}
/// <summary>
/// Declare a exchange passively. Throw an exception rather than create the exchange if it doesn't exist
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The exchange to declare</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void ExchangeDeclarePassive(
this IAdvancedBus bus,
string name,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.ExchangeDeclarePassiveAsync(name, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare an exchange
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The exchange name</param>
/// <param name="type">The type of exchange</param>
/// <param name="durable">Durable exchanges remain active when a server restarts.</param>
/// <param name="autoDelete">If set, the exchange is deleted when all queues have finished using it.</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The exchange</returns>
public static Exchange ExchangeDeclare(
this IAdvancedBus bus,
string name,
string type,
bool durable = true,
bool autoDelete = false,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.ExchangeDeclareAsync(name, type, durable, autoDelete, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Declare an exchange
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="name">The exchange name</param>
/// <param name="configure">The configuration of exchange</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The exchange</returns>
public static Exchange ExchangeDeclare(
this IAdvancedBus bus,
string name,
Action<IExchangeDeclareConfiguration> configure,
CancellationToken cancellationToken = default
)
{
Preconditions.CheckNotNull(bus, nameof(bus));
return bus.ExchangeDeclareAsync(name, configure, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Delete a binding
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="binding">the binding to delete</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void Unbind(this IAdvancedBus bus, Binding<Queue> binding, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.UnbindAsync(binding, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Delete a binding
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="binding">the binding to delete</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void Unbind(this IAdvancedBus bus, Binding<Exchange> binding, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.UnbindAsync(binding, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Delete a queue
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to delete</param>
/// <param name="ifUnused">Only delete if unused</param>
/// <param name="ifEmpty">Only delete if empty</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void QueueDelete(this IAdvancedBus bus, Queue queue, bool ifUnused = false, bool ifEmpty = false, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.QueueDeleteAsync(queue, ifUnused, ifEmpty, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Purges a queue
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="queue">The queue to purge</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void QueuePurge(this IAdvancedBus bus, Queue queue, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.QueuePurgeAsync(queue, cancellationToken)
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Delete an exchange
/// </summary>
/// <param name="bus">The bus instance</param>
/// <param name="exchange">The exchange to delete</param>
/// <param name="ifUnused">If set, the server will only delete the exchange if it has no queue bindings.</param>
/// <param name="cancellationToken">The cancellation token</param>
public static void ExchangeDelete(this IAdvancedBus bus, Exchange exchange, bool ifUnused = false, CancellationToken cancellationToken = default)
{
Preconditions.CheckNotNull(bus, nameof(bus));
bus.ExchangeDeleteAsync(exchange, ifUnused, cancellationToken)
.GetAwaiter()
.GetResult();
}
private class SimpleConsumeConfiguration : ISimpleConsumeConfiguration
{
public bool AutoAck { get; private set; }
public string ConsumerTag { get; private set; }
public bool? IsExclusive { get; private set; }
public ushort? PrefetchCount { get; private set; }
public IDictionary<string, object> Arguments { get; private set; }
public ISimpleConsumeConfiguration WithAutoAck()
{
AutoAck = true;
return this;
}
public ISimpleConsumeConfiguration WithConsumerTag(string consumerTag)
{
ConsumerTag = consumerTag;
return this;
}
public ISimpleConsumeConfiguration WithExclusive(bool isExclusive = true)
{
IsExclusive = isExclusive;
return this;
}
public ISimpleConsumeConfiguration WithArgument(string name, object value)
{
(Arguments ??= new Dictionary<string, object>())[name] = value;
return this;
}
public ISimpleConsumeConfiguration WithPrefetchCount(ushort prefetchCount)
{
PrefetchCount = prefetchCount;
return this;
}
}
}
| |
/* ====================================================================
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 NPOI.SS.Formula.Functions;
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
public class AVEDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.avedev(values);
}
}
public class AVERAGE : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return MathX.Average(values);
}
}
public class DEVSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.devsq(values);
}
}
public class SUM : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Sum(values);
}
}
public class LARGE : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthLargest(values, k);
}
}
public class MAX : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.Max(values) : 0;
}
}
public class MIN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.Min(values) : 0;
}
}
public class MEDIAN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.median(values);
}
}
public class PRODUCT : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Product(values);
}
}
public class SMALL : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthSmallest(values, k);
}
}
public class STDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.stdev(values);
}
}
public class SUMSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Sumsq(values);
}
}
public class VAR : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.var(values);
}
};
public class VARP : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.varp(values);
}
};
public class SubtotalInstance : AggregateFunction
{
private AggregateFunction _func;
public SubtotalInstance(AggregateFunction func)
{
_func = func;
}
protected internal override double Evaluate(double[] values)
{
return _func.Evaluate(values);
}
/**
* ignore nested subtotals.
*/
public override bool IsSubtotalCounted
{
get
{
return false;
}
}
}
public class LargeSmall : Fixed2ArgFunction
{
private bool _isLarge;
protected LargeSmall(bool isLarge)
{
_isLarge = isLarge;
}
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1)
{
double dn;
try
{
ValueEval ve1 = OperandResolver.GetSingleValue(arg1, srcRowIndex, srcColumnIndex);
dn = OperandResolver.CoerceValueToDouble(ve1);
}
catch (EvaluationException)
{
// all errors in the second arg translate to #VALUE!
return ErrorEval.VALUE_INVALID;
}
// weird Excel behaviour on second arg
if (dn < 1.0)
{
// values between 0.0 and 1.0 result in #NUM!
return ErrorEval.NUM_ERROR;
}
// all other values are rounded up to the next integer
int k = (int)Math.Ceiling(dn);
double result;
try
{
double[] ds = NPOI.SS.Formula.Functions.AggregateFunction.ValueCollector.CollectValues(arg0);
if (k > ds.Length)
{
return ErrorEval.NUM_ERROR;
}
result = _isLarge ? StatsLib.kthLargest(ds, k) : StatsLib.kthSmallest(ds, k);
NumericFunction.CheckValue(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
return new NumberEval(result);
}
}
/**
* Returns the k-th percentile of values in a range. You can use this function to establish a threshold of
* acceptance. For example, you can decide to examine candidates who score above the 90th percentile.
*
* PERCENTILE(array,k)
* Array is the array or range of data that defines relative standing.
* K is the percentile value in the range 0..1, inclusive.
*
* <strong>Remarks</strong>
* <ul>
* <li>if array is empty or Contains more than 8,191 data points, PERCENTILE returns the #NUM! error value.</li>
* <li>If k is nonnumeric, PERCENTILE returns the #VALUE! error value.</li>
* <li>If k is < 0 or if k > 1, PERCENTILE returns the #NUM! error value.</li>
* <li>If k is not a multiple of 1/(n - 1), PERCENTILE interpolates to determine the value at the k-th percentile.</li>
* </ul>
*/
public class Percentile : Fixed2ArgFunction
{
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1)
{
double dn;
try
{
ValueEval ve1 = OperandResolver.GetSingleValue(arg1, srcRowIndex, srcColumnIndex);
dn = OperandResolver.CoerceValueToDouble(ve1);
}
catch (EvaluationException)
{
// all errors in the second arg translate to #VALUE!
return ErrorEval.VALUE_INVALID;
}
if (dn < 0 || dn > 1)
{ // has to be percentage
return ErrorEval.NUM_ERROR;
}
double result;
try
{
double[] ds = NPOI.SS.Formula.Functions.AggregateFunction.ValueCollector.CollectValues(arg0);
int N = ds.Length;
if (N == 0 || N > 8191)
{
return ErrorEval.NUM_ERROR;
}
double n = (N - 1) * dn + 1;
if (n == 1d)
{
result = StatsLib.kthSmallest(ds, 1);
}
else if (n == N) //TODO: Double.compare(n, N) == 0, DOSE THE "==" operator equals Double.compare
{
result = StatsLib.kthLargest(ds, 1);
}
else
{
int k = (int)n;
double d = n - k;
result = StatsLib.kthSmallest(ds, k) + d
* (StatsLib.kthSmallest(ds, k + 1) - StatsLib.kthSmallest(ds, k));
}
NumericFunction.CheckValue(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
return new NumberEval(result);
}
}
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public abstract class AggregateFunction : MultiOperandNumericFunction
{
public static Function SubtotalInstance(Function func)
{
AggregateFunction arg = (AggregateFunction)func;
return new SubtotalInstance(arg);
}
internal class ValueCollector : MultiOperandNumericFunction
{
private static ValueCollector instance = new ValueCollector();
public ValueCollector() :
base(false, false)
{
}
public static double[] CollectValues(params ValueEval[] operands)
{
return instance.GetNumberArray(operands);
}
protected internal override double Evaluate(double[] values)
{
throw new InvalidOperationException("should not be called");
}
}
protected AggregateFunction()
: base(false, false)
{
}
public static readonly Function AVEDEV = new AVEDEV();
public static readonly Function AVERAGE = new AVERAGE();
public static readonly Function DEVSQ = new DEVSQ();
public static readonly Function LARGE = new LARGE();
public static readonly Function MAX = new MAX();
public static readonly Function MEDIAN = new MEDIAN();
public static readonly Function MIN = new MIN();
public static readonly Function PRODUCT = new PRODUCT();
public static readonly Function SMALL = new SMALL();
public static readonly Function STDEV = new STDEV();
public static readonly Function SUM = new SUM();
public static readonly Function SUMSQ = new SUMSQ();
public static readonly Function VAR = new VAR();
public static readonly Function VARP = new VARP();
public static readonly Function PERCENTILE = new Percentile();
}
}
| |
// 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.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Test.Common
{
public class Http2LoopbackServer : GenericLoopbackServer, IDisposable
{
private Socket _listenSocket;
private Socket _connectionSocket;
private Stream _connectionStream;
private Http2Options _options;
private Uri _uri;
private bool _ignoreSettingsAck;
private bool _ignoreWindowUpdates;
public Uri Address
{
get
{
var localEndPoint = (IPEndPoint)_listenSocket.LocalEndPoint;
string host = _options.Address.AddressFamily == AddressFamily.InterNetworkV6 ?
$"[{localEndPoint.Address}]" :
localEndPoint.Address.ToString();
string scheme = _options.UseSsl ? "https" : "http";
_uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/");
return _uri;
}
}
public static Http2LoopbackServer CreateServer()
{
return new Http2LoopbackServer(new Http2Options());
}
public static Http2LoopbackServer CreateServer(Http2Options options)
{
return new Http2LoopbackServer(options);
}
private Http2LoopbackServer(Http2Options options)
{
_options = options;
_listenSocket = new Socket(_options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(new IPEndPoint(_options.Address, 0));
_listenSocket.Listen(_options.ListenBacklog);
}
public async Task SendConnectionPrefaceAsync()
{
// Send the initial server settings frame.
Frame emptySettings = new Frame(0, FrameType.Settings, FrameFlags.None, 0);
await WriteFrameAsync(emptySettings).ConfigureAwait(false);
// Receive and ACK the client settings frame.
Frame clientSettings = await ReadFrameAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
clientSettings.Flags = clientSettings.Flags | FrameFlags.Ack;
await WriteFrameAsync(clientSettings).ConfigureAwait(false);
// Receive the client ACK of the server settings frame.
clientSettings = await ReadFrameAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
}
public async Task WriteFrameAsync(Frame frame)
{
byte[] writeBuffer = new byte[Frame.FrameHeaderLength + frame.Length];
frame.WriteTo(writeBuffer);
await _connectionStream.WriteAsync(writeBuffer, 0, writeBuffer.Length).ConfigureAwait(false);
}
// Read until the buffer is full
// Return false on EOF, throw on partial read
private async Task<bool> FillBufferAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
int readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
if (readBytes == 0)
{
return false;
}
buffer = buffer.Slice(readBytes);
while (buffer.Length > 0)
{
readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
if (readBytes == 0)
{
throw new Exception("Connection closed when expecting more data.");
}
buffer = buffer.Slice(readBytes);
}
return true;
}
public async Task<Frame> ReadFrameAsync(TimeSpan timeout)
{
// Prep the timeout cancellation token.
CancellationTokenSource timeoutCts = new CancellationTokenSource(timeout);
// First read the frame headers, which should tell us how long the rest of the frame is.
byte[] headerBytes = new byte[Frame.FrameHeaderLength];
if (!await FillBufferAsync(headerBytes, timeoutCts.Token).ConfigureAwait(false))
{
return null;
}
Frame header = Frame.ReadFrom(headerBytes);
// Read the data segment of the frame, if it is present.
byte[] data = new byte[header.Length];
if (header.Length > 0 && !await FillBufferAsync(data, timeoutCts.Token).ConfigureAwait(false))
{
throw new Exception("Connection stream closed while attempting to read frame body.");
}
if (_ignoreSettingsAck && header.Type == FrameType.Settings && header.Flags == FrameFlags.Ack)
{
_ignoreSettingsAck = false;
return await ReadFrameAsync(timeout);
}
if (_ignoreWindowUpdates && header.Type == FrameType.WindowUpdate)
{
return await ReadFrameAsync(timeout);
}
// Construct the correct frame type and return it.
switch (header.Type)
{
case FrameType.Data:
return DataFrame.ReadFrom(header, data);
case FrameType.Headers:
return HeadersFrame.ReadFrom(header, data);
case FrameType.Priority:
return PriorityFrame.ReadFrom(header, data);
case FrameType.RstStream:
return RstStreamFrame.ReadFrom(header, data);
case FrameType.Ping:
return PingFrame.ReadFrom(header, data);
case FrameType.GoAway:
return GoAwayFrame.ReadFrom(header, data);
default:
return header;
}
}
// Returns the first 24 bytes read, which should be the connection preface.
public async Task<string> AcceptConnectionAsync()
{
if (_connectionSocket != null)
{
throw new InvalidOperationException("Connection already established");
}
_connectionSocket = await _listenSocket.AcceptAsync().ConfigureAwait(false);
_connectionStream = new NetworkStream(_connectionSocket, true);
if (_options.UseSsl)
{
var sslStream = new SslStream(_connectionStream, false, delegate
{ return true; });
using (var cert = Configuration.Certificates.GetServerCertificate())
{
SslServerAuthenticationOptions options = new SslServerAuthenticationOptions();
options.EnabledSslProtocols = _options.SslProtocols;
var protocols = new List<SslApplicationProtocol>();
protocols.Add(SslApplicationProtocol.Http2);
protocols.Add(SslApplicationProtocol.Http11);
options.ApplicationProtocols = protocols;
options.ServerCertificate = cert;
options.ClientCertificateRequired = false;
await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false);
}
_connectionStream = sslStream;
}
byte[] prefix = new byte[24];
if (!await FillBufferAsync(prefix).ConfigureAwait(false))
{
throw new Exception("Connection stream closed while attempting to read connection preface.");
}
return System.Text.Encoding.UTF8.GetString(prefix, 0, prefix.Length);
}
public void ExpectSettingsAck()
{
// The timing of when we receive the settings ack is not guaranteed.
// To simplify frame processing, just record that we are expecting one,
// and then filter it out in ReadFrameAsync above.
Assert.False(_ignoreSettingsAck);
_ignoreSettingsAck = true;
}
public void IgnoreWindowUpdates()
{
_ignoreWindowUpdates = true;
}
// Accept connection and handle connection setup
public async Task EstablishConnectionAsync(params SettingsEntry[] settingsEntries)
{
await AcceptConnectionAsync();
// Receive the initial client settings frame.
Frame receivedFrame = await ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.Settings, receivedFrame.Type);
Assert.Equal(FrameFlags.None, receivedFrame.Flags);
Assert.Equal(0, receivedFrame.StreamId);
// Receive the initial client window update frame.
receivedFrame = await ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.WindowUpdate, receivedFrame.Type);
Assert.Equal(FrameFlags.None, receivedFrame.Flags);
Assert.Equal(0, receivedFrame.StreamId);
// Send the initial server settings frame.
SettingsFrame settingsFrame = new SettingsFrame(settingsEntries);
await WriteFrameAsync(settingsFrame).ConfigureAwait(false);
// Send the client settings frame ACK.
Frame settingsAck = new Frame(0, FrameType.Settings, FrameFlags.Ack, 0);
await WriteFrameAsync(settingsAck).ConfigureAwait(false);
// The client will send us a SETTINGS ACK eventually, but not necessarily right away.
ExpectSettingsAck();
}
public void ShutdownSend()
{
_connectionSocket.Shutdown(SocketShutdown.Send);
}
// This will wait for the client to close the connection,
// and ignore any meaningless frames -- i.e. WINDOW_UPDATE or expected SETTINGS ACK --
// that we see while waiting for the client to close.
// Only call this after sending a GOAWAY.
public async Task WaitForConnectionShutdownAsync()
{
// Shutdown our send side, so the client knows there won't be any more frames coming.
ShutdownSend();
IgnoreWindowUpdates();
Frame frame = await ReadFrameAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
if (frame != null)
{
throw new Exception($"Unexpected frame received while waiting for client shutdown: {frame}");
}
_connectionStream.Close();
_connectionSocket = null;
_connectionStream = null;
_ignoreSettingsAck = false;
_ignoreWindowUpdates = false;
}
public async Task<int> ReadRequestHeaderAsync()
{
// Receive HEADERS frame for request.
Frame frame = await ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders | FrameFlags.EndStream, frame.Flags);
return frame.StreamId;
}
private static (int bytesConsumed, int value) DecodeInteger(ReadOnlySpan<byte> headerBlock, byte prefixMask)
{
int value = headerBlock[0] & prefixMask;
if (value != prefixMask)
{
return (1, value);
}
byte b = headerBlock[1];
if ((b & 0b10000000) != 0)
{
throw new Exception("long integers currently not supported");
}
return (2, prefixMask + b);
}
private static int EncodeInteger(int value, byte prefix, byte prefixMask, Span<byte> headerBlock)
{
byte prefixLimit = (byte)(~prefixMask);
if (value < prefixLimit)
{
headerBlock[0] = (byte)(prefix | value);
return 1;
}
headerBlock[0] = (byte)(prefix | prefixLimit);
int bytesGenerated = 1;
value -= prefixLimit;
while (value >= 0x80)
{
headerBlock[bytesGenerated] = (byte)((value & 0x7F) | 0x80);
value = value >> 7;
bytesGenerated++;
}
headerBlock[bytesGenerated] = (byte)value;
bytesGenerated++;
return bytesGenerated;
}
private static (int bytesConsumed, string value) DecodeString(ReadOnlySpan<byte> headerBlock)
{
(int bytesConsumed, int stringLength) = DecodeInteger(headerBlock, 0b01111111);
if ((headerBlock[0] & 0b10000000) != 0)
{
// Huffman encoded
byte[] buffer = new byte[stringLength * 2];
int bytesDecoded = HuffmanDecoder.Decode(headerBlock.Slice(bytesConsumed, stringLength), buffer);
string value = Encoding.ASCII.GetString(buffer, 0, bytesDecoded);
return (bytesConsumed + stringLength, value);
}
else
{
string value = Encoding.ASCII.GetString(headerBlock.Slice(bytesConsumed, stringLength));
return (bytesConsumed + stringLength, value);
}
}
private static int EncodeString(string value, Span<byte> headerBlock)
{
int bytesGenerated = EncodeInteger(value.Length, 0, 0x80, headerBlock);
bytesGenerated += Encoding.ASCII.GetBytes(value.AsSpan(), headerBlock.Slice(bytesGenerated));
return bytesGenerated;
}
private static readonly HttpHeaderData[] s_staticTable = new HttpHeaderData[]
{
new HttpHeaderData(":authority", ""),
new HttpHeaderData(":method", "GET"),
new HttpHeaderData(":method", "POST"),
new HttpHeaderData(":path", "/"),
new HttpHeaderData(":path", "/index.html"),
new HttpHeaderData(":scheme", "http"),
new HttpHeaderData(":scheme", "https"),
new HttpHeaderData(":status", "200"),
new HttpHeaderData(":status", "204"),
new HttpHeaderData(":status", "206"),
new HttpHeaderData(":status", "304"),
new HttpHeaderData(":status", "400"),
new HttpHeaderData(":status", "404"),
new HttpHeaderData(":status", "500"),
new HttpHeaderData("accept-charset", ""),
new HttpHeaderData("accept-encoding", "gzip, deflate"),
new HttpHeaderData("accept-language", ""),
new HttpHeaderData("accept-ranges", ""),
new HttpHeaderData("accept", ""),
new HttpHeaderData("access-control-allow-origin", ""),
new HttpHeaderData("age", ""),
new HttpHeaderData("allow", ""),
new HttpHeaderData("authorization", ""),
new HttpHeaderData("cache-control", ""),
new HttpHeaderData("content-disposition", ""),
new HttpHeaderData("content-encoding", ""),
new HttpHeaderData("content-language", ""),
new HttpHeaderData("content-length", ""),
new HttpHeaderData("content-location", ""),
new HttpHeaderData("content-range", ""),
new HttpHeaderData("content-type", ""),
new HttpHeaderData("cookie", ""),
new HttpHeaderData("date", ""),
new HttpHeaderData("etag", ""),
new HttpHeaderData("expect", ""),
new HttpHeaderData("expires", ""),
new HttpHeaderData("from", ""),
new HttpHeaderData("host", ""),
new HttpHeaderData("if-match", ""),
new HttpHeaderData("if-modified-since", ""),
new HttpHeaderData("if-none-match", ""),
new HttpHeaderData("if-range", ""),
new HttpHeaderData("if-unmodifiedsince", ""),
new HttpHeaderData("last-modified", ""),
new HttpHeaderData("link", ""),
new HttpHeaderData("location", ""),
new HttpHeaderData("max-forwards", ""),
new HttpHeaderData("proxy-authenticate", ""),
new HttpHeaderData("proxy-authorization", ""),
new HttpHeaderData("range", ""),
new HttpHeaderData("referer", ""),
new HttpHeaderData("refresh", ""),
new HttpHeaderData("retry-after", ""),
new HttpHeaderData("server", ""),
new HttpHeaderData("set-cookie", ""),
new HttpHeaderData("strict-transport-security", ""),
new HttpHeaderData("transfer-encoding", ""),
new HttpHeaderData("user-agent", ""),
new HttpHeaderData("vary", ""),
new HttpHeaderData("via", ""),
new HttpHeaderData("www-authenticate", "")
};
private static HttpHeaderData GetHeaderForIndex(int index)
{
return s_staticTable[index - 1];
}
private static (int bytesConsumed, HttpHeaderData headerData) DecodeLiteralHeader(ReadOnlySpan<byte> headerBlock, byte prefixMask)
{
int i = 0;
(int bytesConsumed, int index) = DecodeInteger(headerBlock, prefixMask);
i += bytesConsumed;
string name;
if (index == 0)
{
(bytesConsumed, name) = DecodeString(headerBlock.Slice(i));
i += bytesConsumed;
}
else
{
name = GetHeaderForIndex(index).Name;
}
string value;
(bytesConsumed, value) = DecodeString(headerBlock.Slice(i));
i += bytesConsumed;
return (i, new HttpHeaderData(name, value));
}
private static (int bytesConsumed, HttpHeaderData headerData) DecodeHeader(ReadOnlySpan<byte> headerBlock)
{
int i = 0;
byte b = headerBlock[0];
if ((b & 0b10000000) != 0)
{
// Indexed header
(int bytesConsumed, int index) = DecodeInteger(headerBlock, 0b01111111);
i += bytesConsumed;
return (i, GetHeaderForIndex(index));
}
else if ((b & 0b11000000) == 0b01000000)
{
// Literal with indexing
return DecodeLiteralHeader(headerBlock, 0b00111111);
}
else if ((b & 0b11100000) == 0b00100000)
{
// Table size update
throw new Exception("table size update not supported");
}
else
{
// Literal, never indexed
return DecodeLiteralHeader(headerBlock, 0b00001111);
}
}
private static int EncodeHeader(HttpHeaderData headerData, Span<byte> headerBlock)
{
// Always encode as literal, no indexing
int bytesGenerated = EncodeInteger(0, 0, 0b11110000, headerBlock);
bytesGenerated += EncodeString(headerData.Name, headerBlock.Slice(bytesGenerated));
bytesGenerated += EncodeString(headerData.Value, headerBlock.Slice(bytesGenerated));
return bytesGenerated;
}
public async Task<(int streamId, HttpRequestData requestData)> ReadAndParseRequestHeaderAsync()
{
HttpRequestData requestData = new HttpRequestData();
// Receive HEADERS frame for request.
HeadersFrame headersFrame = (HeadersFrame) await ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameFlags.EndHeaders | FrameFlags.EndStream, headersFrame.Flags);
int streamId = headersFrame.StreamId;
Memory<byte> data = headersFrame.Data;
int i = 0;
while (i < data.Length)
{
(int bytesConsumed, HttpHeaderData headerData) = DecodeHeader(data.Span.Slice(i));
requestData.Headers.Add(headerData);
i += bytesConsumed;
}
// Extract method and path
requestData.Method = requestData.GetSingleHeaderValue(":method");
requestData.Path = requestData.GetSingleHeaderValue(":path");
return (streamId, requestData);
}
public async Task SendGoAway(int lastStreamId)
{
GoAwayFrame frame = new GoAwayFrame(lastStreamId, 0, new byte[] { }, 0);
await WriteFrameAsync(frame).ConfigureAwait(false);
}
public async Task SendDefaultResponseHeadersAsync(int streamId)
{
byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200"
HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders, 0, 0, 0, streamId);
await WriteFrameAsync(headersFrame).ConfigureAwait(false);
}
public async Task SendDefaultResponseAsync(int streamId)
{
byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200"
HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId);
await WriteFrameAsync(headersFrame).ConfigureAwait(false);
}
public async Task SendResponseHeadersAsync(int streamId, bool endStream = true, HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null)
{
// For now, only support headers that fit in a single frame
byte[] headerBlock = new byte[Frame.MaxFrameLength];
int bytesGenerated = 0;
string statusCodeString = ((int)statusCode).ToString();
bytesGenerated += EncodeHeader(new HttpHeaderData(":status", statusCodeString), headerBlock.AsSpan());
if (headers != null)
{
foreach (HttpHeaderData headerData in headers)
{
bytesGenerated += EncodeHeader(headerData, headerBlock.AsSpan().Slice(bytesGenerated));
}
}
FrameFlags flags = FrameFlags.EndHeaders;
if (endStream)
{
flags |= FrameFlags.EndStream;
}
HeadersFrame headersFrame = new HeadersFrame(headerBlock.AsMemory().Slice(0, bytesGenerated), flags, 0, 0, 0, streamId);
await WriteFrameAsync(headersFrame).ConfigureAwait(false);
}
public async Task SendResponseDataAsync(int streamId, ReadOnlyMemory<byte> responseData, bool endStream)
{
DataFrame dataFrame = new DataFrame(responseData, endStream ? FrameFlags.EndStream : FrameFlags.None, 0, streamId);
await WriteFrameAsync(dataFrame).ConfigureAwait(false);
}
public async Task SendResponseBodyAsync(int streamId, ReadOnlyMemory<byte> responseBody)
{
// Only support response body if it fits in a single frame, for now
// In the future we should separate the body into chunks as needed,
// and if it's larger than the default window size, we will need to process window updates as well.
if (responseBody.Length > Frame.MaxFrameLength)
{
throw new Exception("Response body too long");
}
await SendResponseDataAsync(streamId, responseBody, true);
}
public override void Dispose()
{
if (_listenSocket != null)
{
_listenSocket.Dispose();
_listenSocket = null;
}
}
//
// GenericLoopbackServer implementation
//
public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = null)
{
await EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await ReadAndParseRequestHeaderAsync();
// We are about to close the connection, after we send the response.
// So, send a GOAWAY frame now so the client won't inadvertantly try to reuse the connection.
await SendGoAway(streamId);
if (content == null)
{
await SendResponseHeadersAsync(streamId, true, statusCode, headers);
}
else
{
await SendResponseHeadersAsync(streamId, false, statusCode, headers);
await SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes(content));
}
await WaitForConnectionShutdownAsync();
return requestData;
}
}
public class Http2Options
{
public IPAddress Address { get; set; } = IPAddress.Loopback;
public int ListenBacklog { get; set; } = 1;
public bool UseSsl { get; set; } = true;
public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12;
}
public sealed class Http2LoopbackServerFactory : LoopbackServerFactory
{
public static readonly Http2LoopbackServerFactory Singleton = new Http2LoopbackServerFactory();
public override async Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync)
{
using (var server = Http2LoopbackServer.CreateServer())
{
await funcAsync(server, server.Address);
}
}
public override bool IsHttp11 => false;
public override bool IsHttp2 => true;
}
}
| |
using J2N.Text;
using YAF.Lucene.Net.Diagnostics;
using YAF.Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using Directory = YAF.Lucene.Net.Store.Directory;
namespace YAF.Lucene.Net.Codecs.Lucene3x
{
/*
* 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 FieldInfos = YAF.Lucene.Net.Index.FieldInfos;
using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IOContext = YAF.Lucene.Net.Store.IOContext;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using Term = YAF.Lucene.Net.Index.Term;
/// <summary>
/// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in a
/// Directory. Pairs are accessed either by <see cref="Term"/> or by ordinal position the
/// set.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0) this class has been replaced by FormatPostingsTermsDictReader, except for reading old segments.")]
internal sealed class TermInfosReader : IDisposable
{
private readonly Directory directory;
private readonly string segment;
private readonly FieldInfos fieldInfos;
#pragma warning disable CA2213 // Disposable fields should be disposed
private readonly DisposableThreadLocal<ThreadResources> threadResources = new DisposableThreadLocal<ThreadResources>();
private readonly SegmentTermEnum origEnum;
#pragma warning restore CA2213 // Disposable fields should be disposed
private readonly long size;
private readonly TermInfosReaderIndex index;
private readonly int indexLength;
private readonly int totalIndexInterval;
private const int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
public sealed class TermInfoAndOrd : TermInfo
{
internal readonly long termOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd)
: base(ti)
{
if (Debugging.AssertsEnabled) Debugging.Assert(termOrd >= 0);
this.termOrd = termOrd;
}
}
private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey
{
internal Term term;
public CloneableTerm(Term t)
{
this.term = t;
}
public override bool Equals(object other)
{
CloneableTerm t = (CloneableTerm)other;
return this.term.Equals(t.term);
}
public override int GetHashCode()
{
return term.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override object Clone()
{
return new CloneableTerm(term);
}
}
private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/// <summary>
/// Per-thread resources managed by ThreadLocal.
/// </summary>
private sealed class ThreadResources
{
internal SegmentTermEnum termEnum;
}
internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor)
{
bool success = false;
if (indexDivisor < 1 && indexDivisor != -1)
{
throw new ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try
{
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), fieldInfos, false);
size = origEnum.size;
if (indexDivisor != -1)
{
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
string indexFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(indexFileName, context), fieldInfos, true);
try
{
index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), totalIndexInterval);
indexLength = index.Length;
}
finally
{
indexEnum.Dispose();
}
}
else
{
// Do not load terms index:
totalIndexInterval = -1;
index = null;
indexLength = -1;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
}
public int SkipInterval => origEnum.skipInterval;
public int MaxSkipLevels => origEnum.maxSkipLevels;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
IOUtils.Dispose(origEnum, threadResources);
}
/// <summary>
/// Returns the number of term/value pairs in the set.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal long Count => size;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ThreadResources GetThreadResources()
{
ThreadResources resources = threadResources.Value;
if (resources is null)
{
resources = new ThreadResources();
resources.termEnum = Terms();
threadResources.Value = resources;
}
return resources;
}
private static readonly IComparer<BytesRef> legacyComparer = BytesRef.UTF8SortedAsUTF16Comparer;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CompareAsUTF16(Term term1, Term term2) // LUCENENET: CA1822: Mark members as static
{
if (term1.Field.Equals(term2.Field, StringComparison.Ordinal))
{
return legacyComparer.Compare(term1.Bytes, term2.Bytes);
}
else
{
return term1.Field.CompareToOrdinal(term2.Field);
}
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal TermInfo Get(Term term)
{
return Get(term, false);
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
private TermInfo Get(Term term, bool mustSeekEnum)
{
if (size == 0)
{
return null;
}
EnsureIndexIsRead();
TermInfoAndOrd tiOrd = termsCache.Get(new CloneableTerm(term));
ThreadResources resources = GetThreadResources();
if (!mustSeekEnum && tiOrd != null)
{
return tiOrd;
}
return SeekEnum(resources.termEnum, term, tiOrd, true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CacheCurrentTerm(SegmentTermEnum enumerator)
{
termsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.termInfo, enumerator.position));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Term DeepCopyOf(Term other)
{
return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache)
{
if (useCache)
{
return SeekEnum(enumerator, term, termsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache);
}
else
{
return SeekEnum(enumerator, term, null, useCache);
}
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache)
{
if (size == 0)
{
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current
{
int enumOffset = (int)(enumerator.position / totalIndexInterval) + 1;
if (indexLength == enumOffset || index.CompareTo(term, enumOffset) < 0) // but before end of block
{
// no need to seek
TermInfo ti;
int numScans = enumerator.ScanTo(term);
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti = enumerator.termInfo;
if (numScans > 1)
{
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// this prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd is null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.position));
}
}
else if (Debugging.AssertsEnabled)
{
Debugging.Assert(SameTermInfo(ti, tiOrd, enumerator));
Debugging.Assert((int)enumerator.position == tiOrd.termOrd);
}
}
}
else
{
ti = null;
}
return ti;
}
}
// random-access: must seek
int indexPos;
if (tiOrd != null)
{
indexPos = (int)(tiOrd.termOrd / totalIndexInterval);
}
else
{
// Must do binary search:
indexPos = index.GetIndexOffset(term);
}
index.SeekEnum(enumerator, indexPos);
enumerator.ScanTo(term);
TermInfo ti_;
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti_ = enumerator.termInfo;
if (tiOrd is null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.position));
}
}
else if (Debugging.AssertsEnabled)
{
Debugging.Assert(SameTermInfo(ti_, tiOrd, enumerator));
Debugging.Assert(enumerator.position == tiOrd.termOrd);
}
}
else
{
ti_ = null;
}
return ti_;
}
// called only from asserts
private static bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator) // LUCENENET: CA1822: Mark members as static
{
if (ti1.DocFreq != ti2.DocFreq)
{
return false;
}
if (ti1.FreqPointer != ti2.FreqPointer)
{
return false;
}
if (ti1.ProxPointer != ti2.ProxPointer)
{
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.DocFreq >= enumerator.skipInterval && ti1.SkipOffset != ti2.SkipOffset)
{
return false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureIndexIsRead()
{
if (index is null)
{
throw IllegalStateException.Create("terms index was not loaded when this reader was created");
}
}
/// <summary>
/// Returns the position of a <see cref="Term"/> in the set or -1. </summary>
internal long GetPosition(Term term)
{
if (size == 0)
{
return -1;
}
EnsureIndexIsRead();
int indexOffset = index.GetIndexOffset(term);
SegmentTermEnum enumerator = GetThreadResources().termEnum;
index.SeekEnum(enumerator, indexOffset);
while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next())
{
}
if (CompareAsUTF16(term, enumerator.Term()) == 0)
{
return enumerator.position;
}
else
{
return -1;
}
}
/// <summary>
/// Returns an enumeration of all the <see cref="Term"/>s and <see cref="TermInfo"/>s in the set. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SegmentTermEnum Terms()
{
return (SegmentTermEnum)origEnum.Clone();
}
/// <summary>
/// Returns an enumeration of terms starting at or after the named term. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SegmentTermEnum Terms(Term term)
{
Get(term, true);
return (SegmentTermEnum)GetThreadResources().termEnum.Clone();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal long RamBytesUsed()
{
return index is null ? 0 : index.RamBytesUsed();
}
}
}
| |
// 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.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
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>
/// ReplicationRecoveryServicesProvidersOperations operations.
/// </summary>
internal partial class ReplicationRecoveryServicesProvidersOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationRecoveryServicesProvidersOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationRecoveryServicesProvidersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReplicationRecoveryServicesProvidersOperations(SiteRecoveryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SiteRecoveryManagementClient
/// </summary>
public SiteRecoveryManagementClient Client { get; private set; }
/// <summary>
/// Refresh details from the recovery services provider.
/// </summary>
/// <remarks>
/// The operation to refresh the information from the recovery services
/// provider.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RecoveryServicesProvider>> RefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<RecoveryServicesProvider> _response = await BeginRefreshProviderWithHttpMessagesAsync(fabricName, providerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes provider from fabric. Note: Deleting provider for any fabric other
/// than SingleHost is unsupported. To maintain backward compatibility for
/// released clients the object "deleteRspInput" is used (if the object is
/// empty we assume that it is old client and continue the old behavior).
/// </summary>
/// <remarks>
/// The operation to removes/delete(unregister) a recovery services provider
/// from the vault
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </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 fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(fabricName, providerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the details of a recovery services provider.
/// </summary>
/// <remarks>
/// Gets the details of registered recovery services provider.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name
/// </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<RecoveryServicesProvider>> GetWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (providerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "providerName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("providerName", providerName);
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.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{providerName}", System.Uri.EscapeDataString(providerName));
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<RecoveryServicesProvider>();
_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<RecoveryServicesProvider>(_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>
/// Purges recovery service provider from fabric
/// </summary>
/// <remarks>
/// The operation to purge(force delete) a recovery services provider from the
/// vault.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginPurgeWithHttpMessagesAsync(fabricName, providerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the list of registered recovery services providers for the fabric.
/// </summary>
/// <remarks>
/// Lists the registered recovery services providers for the specified fabric.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name
/// </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<RecoveryServicesProvider>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabrics", 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.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
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<IPage<RecoveryServicesProvider>>();
_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<RecoveryServicesProvider>>(_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>
/// Gets the list of registered recovery services providers in the vault. This
/// is a view only api.
/// </summary>
/// <remarks>
/// Lists the registered recovery services providers in the vault
/// </remarks>
/// <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<RecoveryServicesProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
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("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}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryServicesProviders").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_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<IPage<RecoveryServicesProvider>>();
_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<RecoveryServicesProvider>>(_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>
/// Refresh details from the recovery services provider.
/// </summary>
/// <remarks>
/// The operation to refresh the information from the recovery services
/// provider.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </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<RecoveryServicesProvider>> BeginRefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (providerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "providerName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("providerName", providerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRefreshProvider", 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.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/refreshProvider").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{providerName}", System.Uri.EscapeDataString(providerName));
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("POST");
_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 && (int)_statusCode != 202)
{
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<RecoveryServicesProvider>();
_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<RecoveryServicesProvider>(_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 provider from fabric. Note: Deleting provider for any fabric other
/// than SingleHost is unsupported. To maintain backward compatibility for
/// released clients the object "deleteRspInput" is used (if the object is
/// empty we assume that it is old client and continue the old behavior).
/// </summary>
/// <remarks>
/// The operation to removes/delete(unregister) a recovery services provider
/// from the vault
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </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 fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (providerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "providerName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("providerName", providerName);
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.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/remove").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{providerName}", System.Uri.EscapeDataString(providerName));
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("POST");
_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 != 202 && (int)_statusCode != 204)
{
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>
/// Purges recovery service provider from fabric
/// </summary>
/// <remarks>
/// The operation to purge(force delete) a recovery services provider from the
/// vault.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='providerName'>
/// Recovery services provider name.
/// </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> BeginPurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (providerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "providerName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("providerName", providerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPurge", 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.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{providerName}", System.Uri.EscapeDataString(providerName));
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 (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 != 202 && (int)_statusCode != 204)
{
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>
/// Gets the list of registered recovery services providers for the fabric.
/// </summary>
/// <remarks>
/// Lists the registered recovery services providers for the specified fabric.
/// </remarks>
/// <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<RecoveryServicesProvider>>> ListByReplicationFabricsNextWithHttpMessagesAsync(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, "ListByReplicationFabricsNext", 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<RecoveryServicesProvider>>();
_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<RecoveryServicesProvider>>(_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>
/// Gets the list of registered recovery services providers in the vault. This
/// is a view only api.
/// </summary>
/// <remarks>
/// Lists the registered recovery services providers in the vault
/// </remarks>
/// <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<RecoveryServicesProvider>>> 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<RecoveryServicesProvider>>();
_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<RecoveryServicesProvider>>(_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;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// The ValidatingValue class supports setting a value and validating the
/// value.
/// </summary>
/// <typeparam name="T">
/// The generic parameter.
/// </typeparam>
[Serializable]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public class ValidatingValue<T> : ValidatingValueBase
{
#region Properties
#region Value
private const string ValuePropertyName = "Value";
private object value;
/// <summary>
/// Gets or sets a value.
/// </summary>
public object Value
{
get
{
return this.value;
}
set
{
this.value = value;
this.InvalidateValidationResult();
this.NotifyPropertyChanged(ValuePropertyName);
}
}
#endregion Value
#endregion Properties
#region Public Methods
/// <summary>
/// Gets the raw value cast/transformed into
/// type T.
/// </summary>
/// <returns>
/// The cast value.
/// </returns>
public T GetCastValue()
{
if (!this.IsValid)
{
throw new InvalidOperationException("Cannot return cast value when value is invalid");
}
T castValue;
if (!this.TryGetCastValue(this.Value, out castValue))
{
throw new InvalidOperationException("Validation passed yet a cast value was not retrieved");
}
return castValue;
}
#region ForceValidationUpdate
/// <summary>
/// Forces a validation update to occur.
/// </summary>
/// <remarks>
/// The validation update occurs via signaling that
/// the Value property has changed.
/// </remarks>
public void ForceValidationUpdate()
{
this.NotifyPropertyChanged("Value");
}
#endregion ForceValidationUpdate
#region Validate
/// <summary>
/// Called to validate the entire object.
/// </summary>
/// <returns>
/// Returns a DataErrorInfoValidationResult which indicates the validation state
/// of the object.
/// </returns>
protected override DataErrorInfoValidationResult Validate()
{
return this.Validate(ValuePropertyName);
}
/// <summary>
/// Called to validate the property with the given name.
/// </summary>
/// <param name="columnName">
/// The name of the property whose error message will be checked.
/// </param>
/// <returns>
/// Returns a DataErrorInfoValidationResult which indicates
/// the validation state of the property.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="columnName"/> may only be
/// <see cref="ValuePropertyName"/>.
/// </exception>
protected override DataErrorInfoValidationResult Validate(string columnName)
{
if (!columnName.Equals(ValuePropertyName, StringComparison.Ordinal))
{
throw new ArgumentOutOfRangeException("columnName");
}
if (this.IsValueEmpty())
{
return new DataErrorInfoValidationResult(false, null, string.Empty);
}
T castValue;
if (!this.TryGetCastValue(this.Value, out castValue))
{
string errorMessage = FilterRuleCustomizationFactory.FactoryInstance.GetErrorMessageForInvalidValue(
this.Value.ToString(),
typeof(T));
return new DataErrorInfoValidationResult(
false,
null,
errorMessage);
}
return this.EvaluateValidationRules(castValue, System.Globalization.CultureInfo.CurrentCulture);
}
private bool IsValueEmpty()
{
if (this.Value == null)
{
return true;
}
string stringValue = this.Value.ToString();
if (string.IsNullOrEmpty(stringValue))
{
return true;
}
return false;
}
private bool TryGetCastValue(object rawValue, out T castValue)
{
castValue = default(T);
if (rawValue == null)
{
throw new ArgumentNullException("rawValue");
}
if (typeof(T).IsEnum)
{
return this.TryGetEnumValue(rawValue, out castValue);
}
try
{
castValue = (T)Convert.ChangeType(rawValue, typeof(T), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException)
{
return false;
}
catch (OverflowException)
{
return false;
}
}
private bool TryGetEnumValue(object rawValue, out T castValue)
{
Debug.Assert(rawValue != null, "rawValue not null");
Debug.Assert(typeof(T).IsEnum, "is enum");
castValue = default(T);
try
{
castValue = (T)Enum.Parse(typeof(T), rawValue.ToString(), true);
return true;
}
catch (ArgumentException)
{
return false;
}
}
#endregion Validate
#endregion Public Methods
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
namespace Pathfinding {
public interface INavmesh {
void GetNodes(GraphNodeDelegateCancelable del);
}
[System.Serializable]
[JsonOptIn]
/** Generates graphs based on navmeshes.
\ingroup graphs
Navmeshes are meshes where each polygon define a walkable area.
These are great because the AI can get so much more information on how it can walk.
Polygons instead of points mean that the funnel smoother can produce really nice looking paths and the graphs are also really fast to search
and have a low memory footprint because of their smaller size to describe the same area (compared to grid graphs).
\see Pathfinding.RecastGraph
\shadowimage{navmeshgraph_graph.png}
\shadowimage{navmeshgraph_inspector.png}
*/
public class NavMeshGraph : NavGraph, INavmesh, IUpdatableGraph, IFunnelGraph, INavmeshHolder
{
/** Mesh to construct navmesh from */
[JsonMember]
public Mesh sourceMesh;
/** Offset in world space */
[JsonMember]
public Vector3 offset;
/** Rotation in degrees */
[JsonMember]
public Vector3 rotation;
/** Scale of the graph */
[JsonMember]
public float scale = 1;
/** More accurate nearest node queries.
* When on, looks for the closest point on every triangle instead of if point is inside the node triangle in XZ space.
* This is slower, but a lot better if your mesh contains overlaps (e.g bridges over other areas of the mesh).
* Note that for maximum effect the Full Get Nearest Node Search setting should be toggled in A* Inspector Settings.
*/
[JsonMember]
public bool accurateNearestNode = true;
public TriangleMeshNode[] nodes;
public TriangleMeshNode[] TriNodes {
get { return nodes; }
}
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i=0;i<nodes.Length && del (nodes[i]);i++) {}
}
public override void OnDestroy () {
base.OnDestroy ();
// Cleanup
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this), null);
}
public Int3 GetVertex (int index) {
return vertices[index];
}
public int GetVertexArrayIndex (int index) {
return index;
}
public void GetTileCoordinates (int tileIndex, out int x, out int z) {
//Tiles not supported
x = z = 0;
}
/** Bounding Box Tree. Enables really fast lookups of nodes. \astarpro */
BBTree _bbTree;
public BBTree bbTree {
get { return _bbTree; }
set { _bbTree = value;}
}
[System.NonSerialized]
Int3[] _vertices;
public Int3[] vertices {
get {
return _vertices;
}
set {
_vertices = value;
}
}
[System.NonSerialized]
Vector3[] originalVertices;
[System.NonSerialized]
public int[] triangles;
public void GenerateMatrix () {
SetMatrix (Matrix4x4.TRS (offset,Quaternion.Euler (rotation),new Vector3 (scale,scale,scale)));
}
/** Transforms the nodes using newMatrix from their initial positions.
* The "oldMatrix" variable can be left out in this function call (only for this graph generator)
* since the information can be taken from other saved data, which gives better precision.
*/
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
if (vertices == null || vertices.Length == 0 || originalVertices == null || originalVertices.Length != vertices.Length) {
return;
}
for (int i=0;i<_vertices.Length;i++) {
_vertices[i] = (Int3)newMatrix.MultiplyPoint3x4 (originalVertices[i]);
}
for (int i=0;i<nodes.Length;i++) {
var node = nodes[i];
node.UpdatePositionFromVertices();
if (node.connections != null) {
for (int q=0;q<node.connections.Length;q++) {
node.connectionCosts[q] = (uint)(node.position-node.connections[q].position).costMagnitude;
}
}
}
SetMatrix (newMatrix);
RebuildBBTree (this);
}
public static NNInfo GetNearest (NavMeshGraph graph, GraphNode[] nodes, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
if (nodes == null || nodes.Length == 0) {
Debug.LogError ("NavGraph hasn't been generated yet or does not contain any nodes");
return new NNInfo ();
}
if (constraint == null) constraint = NNConstraint.None;
return GetNearestForceBoth (graph,graph, position, NNConstraint.None, accurateNearestNode);
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearest (this, nodes,position, constraint, accurateNearestNode);
}
/** This performs a linear search through all polygons returning the closest one.
* This is usually only called in the Free version of the A* Pathfinding Project since the Pro one supports BBTrees and will do another query
*/
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearestForce (this, this,position,constraint, accurateNearestNode);
//Debug.LogWarning ("This function shouldn't be called since constrained nodes are sent back in the GetNearest call");
//return new NNInfo ();
}
/** This performs a linear search through all polygons returning the closest one */
public static NNInfo GetNearestForce (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
NNInfo nn = GetNearestForceBoth (graph, navmesh,position,constraint,accurateNearestNode);
nn.node = nn.constrainedNode;
nn.clampedPosition = nn.constClampedPosition;
return nn;
}
/** This performs a linear search through all polygons returning the closest one.
* This will fill the NNInfo with .node for the closest node not necessarily complying with the NNConstraint, and .constrainedNode with the closest node
* complying with the NNConstraint.
* \see GetNearestForce(Node[],Int3[],Vector3,NNConstraint,bool)
*/
public static NNInfo GetNearestForceBoth (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
var pos = (Int3)position;
float minDist = -1;
GraphNode minNode = null;
float minConstDist = -1;
GraphNode minConstNode = null;
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
GraphNodeDelegateCancelable del = delegate (GraphNode _node) {
var node = _node as TriangleMeshNode;
if (accurateNearestNode) {
Vector3 closest = node.ClosestPointOnNode (position);
float dist = ((Vector3)pos-closest).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
if (!node.ContainsPoint ((Int3)position)) {
float dist = (node.position-pos).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
int dist = AstarMath.Abs (node.position.y-pos.y);
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
}
}
return true;
};
graph.GetNodes (del);
var nninfo = new NNInfo (minNode);
//Find the point closest to the nearest triangle
if (nninfo.node != null) {
var node = nninfo.node as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.clampedPosition = clP;
}
nninfo.constrainedNode = minConstNode;
if (nninfo.constrainedNode != null) {
var node = nninfo.constrainedNode as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.constClampedPosition = clP;
}
return nninfo;
}
public void BuildFunnelCorridor (List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
BuildFunnelCorridor (this,path,startIndex,endIndex,left,right);
}
public static void BuildFunnelCorridor (INavmesh graph, List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
if (graph == null) {
Debug.LogError ("Couldn't cast graph to the appropriate type (graph isn't a Navmesh type graph, it doesn't implement the INavmesh interface)");
return;
}
for (int i=startIndex;i<endIndex;i++) {
//Find the connection between the nodes
var n1 = path[i] as TriangleMeshNode;
var n2 = path[i+1] as TriangleMeshNode;
int a;
bool search = true;
for (a=0;a<3;a++) {
for (int b=0;b<3;b++) {
if (n1.GetVertexIndex(a) == n2.GetVertexIndex((b+1)%3) && n1.GetVertexIndex((a+1)%3) == n2.GetVertexIndex(b)) {
search = false;
break;
}
}
if (!search) break;
}
if (a == 3) {
left.Add ((Vector3)n1.position);
right.Add ((Vector3)n1.position);
left.Add ((Vector3)n2.position);
right.Add ((Vector3)n2.position);
} else {
left.Add ((Vector3)n1.GetVertex(a));
right.Add ((Vector3)n1.GetVertex((a+1)%3));
}
}
}
public void AddPortal (GraphNode n1, GraphNode n2, List<Vector3> left, List<Vector3> right) {
}
public GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o) {
return GraphUpdateThreading.UnityThread;
}
public void UpdateAreaInit (GraphUpdateObject o) {}
public void UpdateArea (GraphUpdateObject o) {
UpdateArea (o, this);
}
public static void UpdateArea (GraphUpdateObject o, INavmesh graph) {
Bounds bounds = o.bounds;
// Bounding rectangle with floating point coordinates
Rect r = Rect.MinMaxRect (bounds.min.x,bounds.min.z,bounds.max.x,bounds.max.z);
// Bounding rectangle with int coordinates
var r2 = new IntRect(
Mathf.FloorToInt(bounds.min.x*Int3.Precision),
Mathf.FloorToInt(bounds.min.z*Int3.Precision),
Mathf.FloorToInt(bounds.max.x*Int3.Precision),
Mathf.FloorToInt(bounds.max.z*Int3.Precision)
);
// Corners of the bounding rectangle
var a = new Int3(r2.xmin,0,r2.ymin);
var b = new Int3(r2.xmin,0,r2.ymax);
var c = new Int3(r2.xmax,0,r2.ymin);
var d = new Int3(r2.xmax,0,r2.ymax);
var ymin = ((Int3)bounds.min).y;
var ymax = ((Int3)bounds.max).y;
// Loop through all nodes
graph.GetNodes (_node => {
var node = _node as TriangleMeshNode;
bool inside = false;
int allLeft = 0;
int allRight = 0;
int allTop = 0;
int allBottom = 0;
// Check bounding box rect in XZ plane
for (int v=0;v<3;v++) {
Int3 p = node.GetVertex(v);
var vert = (Vector3)p;
if (r2.Contains (p.x,p.z)) {
inside = true;
break;
}
if (vert.x < r.xMin) allLeft++;
if (vert.x > r.xMax) allRight++;
if (vert.z < r.yMin) allTop++;
if (vert.z > r.yMax) allBottom++;
}
if (!inside) {
if (allLeft == 3 || allRight == 3 || allTop == 3 || allBottom == 3) {
return true;
}
}
// Check if the polygon edges intersect the bounding rect
for (int v = 0; v < 3; v++) {
int v2 = v > 1 ? 0 : v+1;
Int3 vert1 = node.GetVertex(v);
Int3 vert2 = node.GetVertex(v2);
if (Polygon.Intersects (a,b,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (a,c,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (c,d,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (d,b,vert1,vert2)) { inside = true; break; }
}
// Check if the node contains any corner of the bounding rect
if (inside || node.ContainsPoint (a) || node.ContainsPoint (b) || node.ContainsPoint (c) || node.ContainsPoint (d)) {
inside = true;
}
if (!inside) {
return true;
}
int allAbove = 0;
int allBelow = 0;
// Check y coordinate
for (int v = 0; v < 3; v++) {
Int3 p = node.GetVertex(v);
var vert = (Vector3)p;
if (vert.y < ymin) allBelow++;
if (vert.y > ymax) allAbove++;
}
// Polygon is either completely above the bounding box or completely below it
if (allBelow == 3 || allAbove == 3) return true;
// Triangle is inside the bounding box!
// Update it!
o.WillUpdateNode(node);
o.Apply (node);
return true;
});
}
/** Returns the closest point of the node.
* The only reason this is here is because it is slightly faster compared to TriangleMeshNode.ClosestPointOnNode
* since it doesn't involve so many indirections.
*
* Use TriangleMeshNode.ClosestPointOnNode in most other cases.
*/
static Vector3 ClosestPointOnNode (TriangleMeshNode node, Int3[] vertices, Vector3 pos) {
return Polygon.ClosestPointOnTriangle ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],(Vector3)vertices[node.v2],pos);
}
/** Returns if the point is inside the node in XZ space */
[System.Obsolete("Use TriangleMeshNode.ContainsPoint instead")]
public bool ContainsPoint (TriangleMeshNode node, Vector3 pos) {
if ( Polygon.IsClockwise ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Returns if the point is inside the node in XZ space */
[System.Obsolete("Use TriangleMeshNode.ContainsPoint instead")]
public static bool ContainsPoint (TriangleMeshNode node, Vector3 pos, Int3[] vertices) {
if (!Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], (Vector3)vertices[node.v2])) {
Debug.LogError ("Noes!");
}
if ( Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Scans the graph using the path to an .obj mesh */
public void ScanInternal (string objMeshPath) {
Mesh mesh = ObjImporter.ImportFile (objMeshPath);
if (mesh == null) {
Debug.LogError ("Couldn't read .obj file at '"+objMeshPath+"'");
return;
}
sourceMesh = mesh;
var scan = ScanInternal ().GetEnumerator ();
while (scan.MoveNext()) {}
}
public override IEnumerable<Progress> ScanInternal () {
ScanInternal (p => {});
yield break;
}
public void ScanInternal (OnScanStatus statusCallback) {
if (sourceMesh == null) {
return;
}
GenerateMatrix ();
Vector3[] vectorVertices = sourceMesh.vertices;
triangles = sourceMesh.triangles;
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this),this);
GenerateNodes (vectorVertices,triangles, out originalVertices, out _vertices);
}
/** Generates a navmesh. Based on the supplied vertices and triangles */
void GenerateNodes (Vector3[] vectorVertices, int[] triangles, out Vector3[] originalVertices, out Int3[] vertices) {
Profiler.BeginSample ("Init");
if (vectorVertices.Length == 0 || triangles.Length == 0) {
originalVertices = vectorVertices;
vertices = new Int3[0];
nodes = new TriangleMeshNode[0];
return;
}
vertices = new Int3[vectorVertices.Length];
int c = 0;
for (int i=0;i<vertices.Length;i++) {
vertices[i] = (Int3)matrix.MultiplyPoint3x4 (vectorVertices[i]);
}
var hashedVerts = new Dictionary<Int3,int> ();
var newVertices = new int[vertices.Length];
Profiler.EndSample ();
Profiler.BeginSample ("Hashing");
for (int i=0;i<vertices.Length;i++) {
if (!hashedVerts.ContainsKey (vertices[i])) {
newVertices[c] = i;
hashedVerts.Add (vertices[i], c);
c++;
}
}
for (int x=0;x<triangles.Length;x++) {
Int3 vertex = vertices[triangles[x]];
triangles[x] = hashedVerts[vertex];
}
Int3[] totalIntVertices = vertices;
vertices = new Int3[c];
originalVertices = new Vector3[c];
for (int i=0;i<c;i++) {
vertices[i] = totalIntVertices[newVertices[i]];
originalVertices[i] = vectorVertices[newVertices[i]];
}
Profiler.EndSample ();
Profiler.BeginSample ("Constructing Nodes");
nodes = new TriangleMeshNode[triangles.Length/3];
int graphIndex = active.astarData.GetGraphIndex(this);
// Does not have to set this, it is set in ScanInternal
//TriangleMeshNode.SetNavmeshHolder ((int)graphIndex,this);
for (int i=0;i<nodes.Length;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];//new MeshNode ();
node.GraphIndex = (uint)graphIndex;
node.Penalty = initialPenalty;
node.Walkable = true;
node.v0 = triangles[i*3];
node.v1 = triangles[i*3+1];
node.v2 = triangles[i*3+2];
if (!Polygon.IsClockwise (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
//Debug.DrawLine (vertices[node.v0],vertices[node.v1],Color.red);
//Debug.DrawLine (vertices[node.v1],vertices[node.v2],Color.red);
//Debug.DrawLine (vertices[node.v2],vertices[node.v0],Color.red);
int tmp = node.v0;
node.v0 = node.v2;
node.v2 = tmp;
}
if (Polygon.IsColinear (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.red);
}
// Make sure position is correctly set
node.UpdatePositionFromVertices();
}
Profiler.EndSample ();
var sides = new Dictionary<Int2, TriangleMeshNode>();
for (int i=0, j=0;i<triangles.Length; j+=1, i+=3) {
sides[new Int2(triangles[i+0],triangles[i+1])] = nodes[j];
sides[new Int2(triangles[i+1],triangles[i+2])] = nodes[j];
sides[new Int2(triangles[i+2],triangles[i+0])] = nodes[j];
}
Profiler.BeginSample ("Connecting Nodes");
var connections = new List<MeshNode> ();
var connectionCosts = new List<uint> ();
for (int i=0, j = 0; i < triangles.Length; j+=1, i+=3) {
connections.Clear ();
connectionCosts.Clear ();
TriangleMeshNode node = nodes[j];
for ( int q = 0; q < 3; q++ ) {
TriangleMeshNode other;
if (sides.TryGetValue ( new Int2 (triangles[i+((q+1)%3)], triangles[i+q]), out other ) ) {
connections.Add (other);
connectionCosts.Add ((uint)(node.position-other.position).costMagnitude);
}
}
node.connections = connections.ToArray ();
node.connectionCosts = connectionCosts.ToArray ();
}
Profiler.EndSample ();
Profiler.BeginSample ("Rebuilding BBTree");
RebuildBBTree (this);
Profiler.EndSample ();
}
/** Rebuilds the BBTree on a NavGraph.
* \astarpro
* \see NavMeshGraph.bbTree */
public static void RebuildBBTree (NavMeshGraph graph) {
// BBTree is an A* Pathfinding Project Pro only feature - The Pro version can be bought in the Unity Asset Store or on arongranberg.com
}
public void PostProcess () {
}
public override void OnDrawGizmos (bool drawNodes) {
if (!drawNodes) {
return;
}
Matrix4x4 preMatrix = matrix;
GenerateMatrix ();
if (nodes == null) {
//Scan ();
}
if (nodes == null) {
return;
}
if (preMatrix != matrix) {
//Debug.Log ("Relocating Nodes");
RelocateNodes (preMatrix, matrix);
}
PathHandler debugData = AstarPath.active.debugPathData;
for (int i=0;i<nodes.Length;i++) {
var node = nodes[i];
Gizmos.color = NodeColor (node,AstarPath.active.debugPathData);
if (node.Walkable ) {
if (AstarPath.active.showSearchTree && debugData != null && debugData.GetPathNode(node).parent != null) {
Gizmos.DrawLine ((Vector3)node.position,(Vector3)debugData.GetPathNode(node).parent.node.position);
} else {
for (int q=0;q<node.connections.Length;q++) {
Gizmos.DrawLine ((Vector3)node.position,Vector3.Lerp ((Vector3)node.position, (Vector3)node.connections[q].position, 0.45f));
}
}
Gizmos.color = AstarColor.MeshEdgeColor;
} else {
Gizmos.color = AstarColor.UnwalkableNode;
}
Gizmos.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1]);
Gizmos.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2]);
Gizmos.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0]);
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx) {
uint graphIndex = (uint)ctx.graphIndex;
TriangleMeshNode.SetNavmeshHolder ((int)graphIndex,this);
int nodeCount = ctx.reader.ReadInt32();
int vertexCount = ctx.reader.ReadInt32();
if (nodeCount == -1) {
nodes = new TriangleMeshNode[0];
_vertices = new Int3[0];
originalVertices = new Vector3[0];
}
nodes = new TriangleMeshNode[nodeCount];
_vertices = new Int3[vertexCount];
originalVertices = new Vector3[vertexCount];
for (int i=0;i<vertexCount;i++) {
_vertices[i] = new Int3(ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
originalVertices[i] = new Vector3(ctx.reader.ReadSingle(), ctx.reader.ReadSingle(), ctx.reader.ReadSingle());
}
for (int i = 0; i < nodeCount;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];
node.DeserializeNode(ctx);
node.UpdatePositionFromVertices();
}
}
public override void SerializeExtraInfo (GraphSerializationContext ctx) {
if (nodes == null || originalVertices == null || _vertices == null || originalVertices.Length != _vertices.Length) {
ctx.writer.Write (-1);
ctx.writer.Write (-1);
return;
}
ctx.writer.Write(nodes.Length);
ctx.writer.Write(_vertices.Length);
for (int i=0;i<_vertices.Length;i++) {
ctx.writer.Write (_vertices[i].x);
ctx.writer.Write (_vertices[i].y);
ctx.writer.Write (_vertices[i].z);
ctx.writer.Write (originalVertices[i].x);
ctx.writer.Write (originalVertices[i].y);
ctx.writer.Write (originalVertices[i].z);
}
for (int i=0;i<nodes.Length;i++) {
nodes[i].SerializeNode (ctx);
}
}
#if ASTAR_NO_JSON
public override void SerializeSettings ( GraphSerializationContext ctx ) {
base.SerializeSettings (ctx);
ctx.SerializeUnityObject ( sourceMesh );
ctx.SerializeVector3 (offset);
ctx.SerializeVector3 (rotation);
ctx.writer.Write(scale);
ctx.writer.Write(accurateNearestNode);
}
public override void DeserializeSettings ( GraphSerializationContext ctx ) {
base.DeserializeSettings (ctx);
sourceMesh = ctx.DeserializeUnityObject () as Mesh;
offset = ctx.DeserializeVector3 ();
rotation = ctx.DeserializeVector3 ();
scale = ctx.reader.ReadSingle();
accurateNearestNode = ctx.reader.ReadBoolean();
}
#endif
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using Orleans.Runtime;
using Orleans.Concurrency;
using Orleans.CodeGeneration;
namespace Orleans.Serialization
{
internal static class BuiltInTypes
{
#region Constants
private static readonly Type objectType = typeof(object);
#endregion
#region Generic collections
#region Lists
internal static void SerializeGenericList(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeList", "DeserializeList", "DeepCopyList", generics);
concretes.Item1(original, stream, expected);
}
internal static object DeserializeGenericList(Type expected, BinaryTokenStreamReader stream)
{
var generics = expected.GetGenericArguments();
var concretes = RegisterConcreteMethods(expected, "SerializeList", "DeserializeList", "DeepCopyList", generics);
return concretes.Item2(expected, stream);
}
internal static object CopyGenericList(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeList", "DeserializeList", "DeepCopyList", generics);
return concretes.Item3(original);
}
internal static void SerializeList<T>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var list = (List<T>)obj;
stream.Write(list.Count);
foreach (var element in list)
{
SerializationManager.SerializeInner(element, stream, typeof(T));
}
}
internal static object DeserializeList<T>(Type expected, BinaryTokenStreamReader stream)
{
var count = stream.ReadInt();
var list = new List<T>(count);
for (var i = 0; i < count; i++)
{
list.Add((T)SerializationManager.DeserializeInner(typeof(T), stream));
}
return list;
}
internal static object DeepCopyList<T>(object original)
{
var list = (List<T>)original;
if (typeof(T).IsOrleansShallowCopyable())
{
return new List<T>(list);
}
// set the list capacity, to avoid list resizing.
var retVal = new List<T>(list.Count);
SerializationContext.Current.RecordObject(original, retVal);
retVal.AddRange(list.Select(element => (T)SerializationManager.DeepCopyInner(element)));
return retVal;
}
#endregion
#region LinkedLists
internal static void SerializeGenericLinkedList(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics);
concretes.Item1(original, stream, expected);
}
internal static object DeserializeGenericLinkedList(Type expected, BinaryTokenStreamReader stream)
{
var generics = expected.GetGenericArguments();
var concretes = RegisterConcreteMethods(expected, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics);
return concretes.Item2(expected, stream);
}
internal static object CopyGenericLinkedList(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics);
return concretes.Item3(original);
}
internal static void SerializeLinkedList<T>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var list = (LinkedList<T>)obj;
stream.Write(list.Count);
foreach (var element in list)
{
SerializationManager.SerializeInner(element, stream, typeof(T));
}
}
internal static object DeserializeLinkedList<T>(Type expected, BinaryTokenStreamReader stream)
{
var count = stream.ReadInt();
var list = new LinkedList<T>();
for (var i = 0; i < count; i++)
{
list.AddLast((T)SerializationManager.DeserializeInner(typeof(T), stream));
}
return list;
}
internal static object DeepCopyLinkedList<T>(object original)
{
var list = (LinkedList<T>)original;
if (typeof(T).IsOrleansShallowCopyable())
{
return new LinkedList<T>(list);
}
var retVal = new LinkedList<T>();
SerializationContext.Current.RecordObject(original, retVal);
foreach (var item in list)
{
retVal.AddLast((T)SerializationManager.DeepCopyInner(item));
}
return retVal;
}
#endregion
#region HashSets
internal static void SerializeGenericHashSet(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics);
concretes.Item1(original, stream, expected);
}
internal static object DeserializeGenericHashSet(Type expected, BinaryTokenStreamReader stream)
{
var generics = expected.GetGenericArguments();
var concretes = RegisterConcreteMethods(expected, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics);
return concretes.Item2(expected, stream);
}
internal static object CopyGenericHashSet(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics);
return concretes.Item3(original);
}
internal static void SerializeHashSet<T>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var set = (HashSet<T>)obj;
SerializationManager.SerializeInner(set.Comparer.Equals(EqualityComparer<T>.Default) ? null : set.Comparer,
stream, typeof(IEqualityComparer<T>));
stream.Write(set.Count);
foreach (var element in set)
{
SerializationManager.SerializeInner(element, stream, typeof(T));
}
}
internal static object DeserializeHashSet<T>(Type expected, BinaryTokenStreamReader stream)
{
var comparer =
(IEqualityComparer<T>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<T>), stream);
var count = stream.ReadInt();
var set = new HashSet<T>(comparer);
for (var i = 0; i < count; i++)
{
set.Add((T)SerializationManager.DeserializeInner(typeof(T), stream));
}
return set;
}
internal static object DeepCopyHashSet<T>(object original)
{
var set = (HashSet<T>)original;
if (typeof(T).IsOrleansShallowCopyable())
{
return new HashSet<T>(set, set.Comparer);
}
var retVal = new HashSet<T>(set.Comparer);
SerializationContext.Current.RecordObject(original, retVal);
foreach (var item in set)
{
retVal.Add((T)SerializationManager.DeepCopyInner(item));
}
return retVal;
}
#endregion
#region Queues
internal static void SerializeGenericQueue(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics);
concretes.Item1(original, stream, expected);
}
internal static object DeserializeGenericQueue(Type expected, BinaryTokenStreamReader stream)
{
var generics = expected.GetGenericArguments();
var concretes = RegisterConcreteMethods(expected, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics);
return concretes.Item2(expected, stream);
}
internal static object CopyGenericQueue(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics);
return concretes.Item3(original);
}
internal static void SerializeQueue<T>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var queue = (Queue<T>)obj;
stream.Write(queue.Count);
foreach (var element in queue)
{
SerializationManager.SerializeInner(element, stream, typeof(T));
}
}
internal static object DeserializeQueue<T>(Type expected, BinaryTokenStreamReader stream)
{
var count = stream.ReadInt();
var queue = new Queue<T>();
for (var i = 0; i < count; i++)
{
queue.Enqueue((T)SerializationManager.DeserializeInner(typeof(T), stream));
}
return queue;
}
internal static object DeepCopyQueue<T>(object original)
{
var queue = (Queue<T>)original;
if (typeof(T).IsOrleansShallowCopyable())
{
return new Queue<T>(queue);
}
var retVal = new Queue<T>(queue.Count);
SerializationContext.Current.RecordObject(original, retVal);
foreach (var item in queue)
{
retVal.Enqueue((T)SerializationManager.DeepCopyInner(item));
}
return retVal;
}
#endregion
#region Stacks
internal static void SerializeGenericStack(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics);
concretes.Item1(original, stream, expected);
}
internal static object DeserializeGenericStack(Type expected, BinaryTokenStreamReader stream)
{
var generics = expected.GetGenericArguments();
var concretes = RegisterConcreteMethods(expected, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics);
return concretes.Item2(expected, stream);
}
internal static object CopyGenericStack(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics);
return concretes.Item3(original);
}
internal static void SerializeStack<T>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var stack = (Stack<T>)obj;
stream.Write(stack.Count);
foreach (var element in stack)
{
SerializationManager.SerializeInner(element, stream, typeof(T));
}
}
internal static object DeserializeStack<T>(Type expected, BinaryTokenStreamReader stream)
{
var count = stream.ReadInt();
var list = new List<T>(count);
for (var i = 0; i < count; i++)
{
list.Add((T)SerializationManager.DeserializeInner(typeof(T), stream));
}
list.Reverse(); // NOTE: this is required to get things on the stack in the original order
var stack = new Stack<T>(list);
return stack;
}
internal static object DeepCopyStack<T>(object original)
{
var stack = (Stack<T>)original;
if (typeof(T).IsOrleansShallowCopyable())
{
return new Stack<T>(stack.Reverse()); // NOTE: Yes, the Reverse really is required
}
var retVal = new Stack<T>();
SerializationContext.Current.RecordObject(original, retVal);
foreach (var item in stack.Reverse())
{
retVal.Push((T)SerializationManager.DeepCopyInner(item));
}
return retVal;
}
#endregion
#region Dictionaries
internal static void SerializeGenericDictionary(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericDictionary(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericDictionary(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary");
return concreteMethods.Item3(original);
}
internal static void SerializeDictionary<K, V>(object original, BinaryTokenStreamWriter stream, Type expected)
{
var dict = (Dictionary<K, V>)original;
SerializationManager.SerializeInner(dict.Comparer.Equals(EqualityComparer<K>.Default) ? null : dict.Comparer,
stream, typeof (IEqualityComparer<K>));
stream.Write(dict.Count);
foreach (var pair in dict)
{
SerializationManager.SerializeInner(pair.Key, stream, typeof(K));
SerializationManager.SerializeInner(pair.Value, stream, typeof(V));
}
}
internal static object DeserializeDictionary<K, V>(Type expected, BinaryTokenStreamReader stream)
{
var comparer = (IEqualityComparer<K>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<K>), stream);
var count = stream.ReadInt();
var dict = new Dictionary<K, V>(count, comparer);
for (var i = 0; i < count; i++)
{
var key = (K)SerializationManager.DeserializeInner(typeof(K), stream);
var value = (V)SerializationManager.DeserializeInner(typeof(V), stream);
dict[key] = value;
}
return dict;
}
internal static object CopyDictionary<K, V>(object original)
{
var dict = (Dictionary<K, V>)original;
if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable())
{
return new Dictionary<K, V>(dict, dict.Comparer);
}
var result = new Dictionary<K, V>(dict.Count, dict.Comparer);
SerializationContext.Current.RecordObject(original, result);
foreach (var pair in dict)
{
result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value);
}
return result;
}
internal static void SerializeStringObjectDictionary(object original, BinaryTokenStreamWriter stream, Type expected)
{
var dict = (Dictionary<string, object>)original;
SerializationManager.SerializeInner(dict.Comparer.Equals(EqualityComparer<string>.Default) ? null : dict.Comparer,
stream, typeof(IEqualityComparer<string>));
stream.Write(dict.Count);
foreach (var pair in dict)
{
//stream.WriteTypeHeader(stringType, stringType);
stream.Write(pair.Key);
SerializationManager.SerializeInner(pair.Value, stream, objectType);
}
}
internal static object DeserializeStringObjectDictionary(Type expected, BinaryTokenStreamReader stream)
{
var comparer = (IEqualityComparer<string>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<string>), stream);
var count = stream.ReadInt();
var dict = new Dictionary<string, object>(count, comparer);
for (var i = 0; i < count; i++)
{
//stream.ReadFullTypeHeader(stringType); // Skip the type header, which will be string
var key = stream.ReadString();
var value = SerializationManager.DeserializeInner(null, stream);
dict[key] = value;
}
return dict;
}
internal static object CopyStringObjectDictionary(object original)
{
var dict = (Dictionary<string, object>)original;
var result = new Dictionary<string, object>(dict.Count, dict.Comparer);
SerializationContext.Current.RecordObject(original, result);
foreach (var pair in dict)
{
result[pair.Key] = SerializationManager.DeepCopyInner(pair.Value);
}
return result;
}
#endregion
#region SortedDictionaries
internal static void SerializeGenericSortedDictionary(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericSortedDictionary(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericSortedDictionary(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary");
return concreteMethods.Item3(original);
}
internal static void SerializeSortedDictionary<K, V>(object original, BinaryTokenStreamWriter stream, Type expected)
{
var dict = (SortedDictionary<K, V>)original;
SerializationManager.SerializeInner(dict.Comparer.Equals(Comparer<K>.Default) ? null : dict.Comparer, stream, typeof(IComparer<K>));
stream.Write(dict.Count);
foreach (var pair in dict)
{
SerializationManager.SerializeInner(pair.Key, stream, typeof(K));
SerializationManager.SerializeInner(pair.Value, stream, typeof(V));
}
}
internal static object DeserializeSortedDictionary<K, V>(Type expected, BinaryTokenStreamReader stream)
{
var comparer = (IComparer<K>)SerializationManager.DeserializeInner(typeof(IComparer<K>), stream);
var count = stream.ReadInt();
var dict = new SortedDictionary<K, V>(comparer);
for (var i = 0; i < count; i++)
{
var key = (K)SerializationManager.DeserializeInner(typeof(K), stream);
var value = (V)SerializationManager.DeserializeInner(typeof(V), stream);
dict[key] = value;
}
return dict;
}
internal static object CopySortedDictionary<K, V>(object original)
{
var dict = (SortedDictionary<K, V>)original;
if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable())
{
return new SortedDictionary<K, V>(dict, dict.Comparer);
}
var result = new SortedDictionary<K, V>(dict.Comparer);
SerializationContext.Current.RecordObject(original, result);
foreach (var pair in dict)
{
result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value);
}
return result;
}
#endregion
#region SortedLists
internal static void SerializeGenericSortedList(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedList", "DeserializeSortedList", "CopySortedList");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericSortedList(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeSortedList", "DeserializeSortedList", "CopySortedList");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericSortedList(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedList", "DeserializeSortedList", "CopySortedList");
return concreteMethods.Item3(original);
}
internal static void SerializeSortedList<K, V>(object original, BinaryTokenStreamWriter stream, Type expected)
{
var list = (SortedList<K, V>)original;
SerializationManager.SerializeInner(list.Comparer.Equals(Comparer<K>.Default) ? null : list.Comparer, stream, typeof(IComparer<K>));
stream.Write(list.Count);
foreach (var pair in list)
{
SerializationManager.SerializeInner(pair.Key, stream, typeof(K));
SerializationManager.SerializeInner(pair.Value, stream, typeof(V));
}
}
internal static object DeserializeSortedList<K, V>(Type expected, BinaryTokenStreamReader stream)
{
var comparer = (IComparer<K>)SerializationManager.DeserializeInner(typeof(IComparer<K>), stream);
var count = stream.ReadInt();
var list = new SortedList<K, V>(count, comparer);
for (var i = 0; i < count; i++)
{
var key = (K)SerializationManager.DeserializeInner(typeof(K), stream);
var value = (V)SerializationManager.DeserializeInner(typeof(V), stream);
list[key] = value;
}
return list;
}
internal static object CopySortedList<K, V>(object original)
{
var list = (SortedList<K, V>)original;
if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable())
{
return new SortedList<K, V>(list, list.Comparer);
}
var result = new SortedList<K, V>(list.Count, list.Comparer);
SerializationContext.Current.RecordObject(original, result);
foreach (var pair in list)
{
result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value);
}
return result;
}
#endregion
#endregion
#region Other generics
#region Tuples
internal static void SerializeTuple(object raw, BinaryTokenStreamWriter stream, Type expected)
{
Type t = raw.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics);
concretes.Item1(raw, stream, expected);
}
internal static object DeserializeTuple(Type t, BinaryTokenStreamReader stream)
{
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics);
return concretes.Item2(t, stream);
}
internal static object DeepCopyTuple(object original)
{
Type t = original.GetType();
var generics = t.GetGenericArguments();
var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics);
return concretes.Item3(original);
}
internal static object DeepCopyTuple1<T1>(object original)
{
var input = (Tuple<T1>)original;
var result = new Tuple<T1>((T1)SerializationManager.DeepCopyInner(input.Item1));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple1<T1>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
}
internal static object DeserializeTuple1<T1>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
return new Tuple<T1>(item1);
}
internal static object DeepCopyTuple2<T1, T2>(object original)
{
var input = (Tuple<T1, T2>)original;
var result = new Tuple<T1, T2>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple2<T1, T2>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
}
internal static object DeserializeTuple2<T1, T2>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
return new Tuple<T1, T2>(item1, item2);
}
internal static object DeepCopyTuple3<T1, T2, T3>(object original)
{
var input = (Tuple<T1, T2, T3>)original;
var result = new Tuple<T1, T2, T3>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2),
(T3)SerializationManager.DeepCopyInner(input.Item3));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple3<T1, T2, T3>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2, T3>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
SerializationManager.SerializeInner(input.Item3, stream, typeof(T3));
}
internal static object DeserializeTuple3<T1, T2, T3>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream);
return new Tuple<T1, T2, T3>(item1, item2, item3);
}
internal static object DeepCopyTuple4<T1, T2, T3, T4>(object original)
{
var input = (Tuple<T1, T2, T3, T4>)original;
var result = new Tuple<T1, T2, T3, T4>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2),
(T3)SerializationManager.DeepCopyInner(input.Item3),
(T4)SerializationManager.DeepCopyInner(input.Item4));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple4<T1, T2, T3, T4>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2, T3, T4>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
SerializationManager.SerializeInner(input.Item3, stream, typeof(T3));
SerializationManager.SerializeInner(input.Item4, stream, typeof(T4));
}
internal static object DeserializeTuple4<T1, T2, T3, T4>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream);
var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream);
return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4);
}
internal static object DeepCopyTuple5<T1, T2, T3, T4, T5>(object original)
{
var input = (Tuple<T1, T2, T3, T4, T5>)original;
var result = new Tuple<T1, T2, T3, T4, T5>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2),
(T3)SerializationManager.DeepCopyInner(input.Item3),
(T4)SerializationManager.DeepCopyInner(input.Item4),
(T5)SerializationManager.DeepCopyInner(input.Item5));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple5<T1, T2, T3, T4, T5>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2, T3, T4, T5>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
SerializationManager.SerializeInner(input.Item3, stream, typeof(T3));
SerializationManager.SerializeInner(input.Item4, stream, typeof(T4));
SerializationManager.SerializeInner(input.Item5, stream, typeof(T5));
}
internal static object DeserializeTuple5<T1, T2, T3, T4, T5>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream);
var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream);
var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream);
return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
}
internal static object DeepCopyTuple6<T1, T2, T3, T4, T5, T6>(object original)
{
var input = (Tuple<T1, T2, T3, T4, T5, T6>)original;
var result = new Tuple<T1, T2, T3, T4, T5, T6>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2),
(T3)SerializationManager.DeepCopyInner(input.Item3),
(T4)SerializationManager.DeepCopyInner(input.Item4),
(T5)SerializationManager.DeepCopyInner(input.Item5),
(T6)SerializationManager.DeepCopyInner(input.Item6));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple6<T1, T2, T3, T4, T5, T6>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2, T3, T4, T5, T6>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
SerializationManager.SerializeInner(input.Item3, stream, typeof(T3));
SerializationManager.SerializeInner(input.Item4, stream, typeof(T4));
SerializationManager.SerializeInner(input.Item5, stream, typeof(T5));
SerializationManager.SerializeInner(input.Item6, stream, typeof(T6));
}
internal static object DeserializeTuple6<T1, T2, T3, T4, T5, T6>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream);
var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream);
var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream);
var item6 = (T6)SerializationManager.DeserializeInner(typeof(T6), stream);
return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
}
internal static object DeepCopyTuple7<T1, T2, T3, T4, T5, T6, T7>(object original)
{
var input = (Tuple<T1, T2, T3, T4, T5, T6, T7>)original;
var result = new Tuple<T1, T2, T3, T4, T5, T6, T7>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2),
(T3)SerializationManager.DeepCopyInner(input.Item3),
(T4)SerializationManager.DeepCopyInner(input.Item4),
(T5)SerializationManager.DeepCopyInner(input.Item5),
(T6)SerializationManager.DeepCopyInner(input.Item6),
(T7)SerializationManager.DeepCopyInner(input.Item7));
SerializationContext.Current.RecordObject(original, result);
return result;
}
internal static void SerializeTuple7<T1, T2, T3, T4, T5, T6, T7>(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (Tuple<T1, T2, T3, T4, T5, T6, T7>)obj;
SerializationManager.SerializeInner(input.Item1, stream, typeof(T1));
SerializationManager.SerializeInner(input.Item2, stream, typeof(T2));
SerializationManager.SerializeInner(input.Item3, stream, typeof(T3));
SerializationManager.SerializeInner(input.Item4, stream, typeof(T4));
SerializationManager.SerializeInner(input.Item5, stream, typeof(T5));
SerializationManager.SerializeInner(input.Item6, stream, typeof(T6));
SerializationManager.SerializeInner(input.Item7, stream, typeof(T7));
}
internal static object DeserializeTuple7<T1, T2, T3, T4, T5, T6, T7>(Type expected, BinaryTokenStreamReader stream)
{
var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream);
var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream);
var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream);
var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream);
var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream);
var item6 = (T6)SerializationManager.DeserializeInner(typeof(T6), stream);
var item7 = (T7)SerializationManager.DeserializeInner(typeof(T7), stream);
return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
}
#endregion
#region KeyValuePairs
internal static void SerializeGenericKeyValuePair(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericKeyValuePair(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericKeyValuePair(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair");
return concreteMethods.Item3(original);
}
internal static void SerializeKeyValuePair<TK, TV>(object original, BinaryTokenStreamWriter stream, Type expected)
{
var pair = (KeyValuePair<TK, TV>)original;
SerializationManager.SerializeInner(pair.Key, stream, typeof(TK));
SerializationManager.SerializeInner(pair.Value, stream, typeof(TV));
}
internal static object DeserializeKeyValuePair<K, V>(Type expected, BinaryTokenStreamReader stream)
{
var key = (K)SerializationManager.DeserializeInner(typeof(K), stream);
var value = (V)SerializationManager.DeserializeInner(typeof(V), stream);
return new KeyValuePair<K, V>(key, value);
}
internal static object CopyKeyValuePair<TK, TV>(object original)
{
var pair = (KeyValuePair<TK, TV>)original;
if (typeof(TK).IsOrleansShallowCopyable() && typeof(TV).IsOrleansShallowCopyable())
{
return pair; // KeyValuePair is a struct, so there's already been a copy at this point
}
var result = new KeyValuePair<TK, TV>((TK)SerializationManager.DeepCopyInner(pair.Key), (TV)SerializationManager.DeepCopyInner(pair.Value));
SerializationContext.Current.RecordObject(original, result);
return result;
}
#endregion
#region Nullables
internal static void SerializeGenericNullable(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeNullable", "DeserializeNullable", "CopyNullable");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericNullable(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeNullable", "DeserializeNullable", "CopyNullable");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericNullable(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeNullable", "DeserializeNullable", "CopyNullable");
return concreteMethods.Item3(original);
}
internal static void SerializeNullable<T>(object original, BinaryTokenStreamWriter stream, Type expected) where T : struct
{
var obj = (T?)original;
if (obj.HasValue)
{
SerializationManager.SerializeInner(obj.Value, stream, typeof(T));
}
else
{
stream.WriteNull();
}
}
internal static object DeserializeNullable<T>(Type expected, BinaryTokenStreamReader stream) where T : struct
{
if (stream.PeekToken() == SerializationTokenType.Null)
{
stream.ReadToken();
return new T?();
}
var val = (T) SerializationManager.DeserializeInner(typeof (T), stream);
return new Nullable<T>(val);
}
internal static object CopyNullable<T>(object original) where T : struct
{
return original; // Everything is a struct, so a direct copy is fine
}
#endregion
#region Immutables
internal static void SerializeGenericImmutable(object original, BinaryTokenStreamWriter stream, Type expected)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable");
concreteMethods.Item1(original, stream, expected);
}
internal static object DeserializeGenericImmutable(Type expected, BinaryTokenStreamReader stream)
{
var concreteMethods = RegisterConcreteMethods(expected, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable");
return concreteMethods.Item2(expected, stream);
}
internal static object CopyGenericImmutable(object original)
{
Type t = original.GetType();
var concreteMethods = RegisterConcreteMethods(t, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable");
return concreteMethods.Item3(original);
}
internal static void SerializeImmutable<T>(object original, BinaryTokenStreamWriter stream, Type expected)
{
var obj = (Immutable<T>) original;
SerializationManager.SerializeInner(obj.Value, stream, typeof(T));
}
internal static object DeserializeImmutable<T>(Type expected, BinaryTokenStreamReader stream)
{
var val = (T)SerializationManager.DeserializeInner(typeof(T), stream);
return new Immutable<T>(val);
}
internal static object CopyImmutable<T>(object original)
{
return original; // Immutable means never having to make a copy...
}
#endregion
#endregion
#region Other System types
#region TimeSpan
internal static void SerializeTimeSpan(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var ts = (TimeSpan)obj;
stream.Write(ts.Ticks);
}
internal static object DeserializeTimeSpan(Type expected, BinaryTokenStreamReader stream)
{
return new TimeSpan(stream.ReadLong());
}
internal static object CopyTimeSpan(object obj)
{
return obj; // TimeSpan is a value type
}
#endregion
#region DateTimeOffset
internal static void SerializeDateTimeOffset(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var dts = (DateTimeOffset)obj;
stream.Write(dts.DateTime.Ticks);
stream.Write(dts.Offset.Ticks);
}
internal static object DeserializeDateTimeOffset(Type expected, BinaryTokenStreamReader stream)
{
return new DateTimeOffset(stream.ReadLong(), new TimeSpan(stream.ReadLong()));
}
internal static object CopyDateTimeOffset(object obj)
{
return obj; // DateTimeOffset is a value type
}
#endregion
#region Type
internal static void SerializeType(object obj, BinaryTokenStreamWriter stream, Type expected)
{
stream.Write(((Type)obj).OrleansTypeName());
}
internal static object DeserializeType(Type expected, BinaryTokenStreamReader stream)
{
return SerializationManager.ResolveTypeName(stream.ReadString());
}
internal static object CopyType(object obj)
{
return obj; // Type objects are effectively immutable
}
#endregion Type
#region GUID
internal static void SerializeGuid(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var guid = (Guid) obj;
stream.Write(guid.ToByteArray());
}
internal static object DeserializeGuid(Type expected, BinaryTokenStreamReader stream)
{
var bytes = stream.ReadBytes(16);
return new Guid(bytes);
}
internal static object CopyGuid(object obj)
{
return obj; // Guids are value types
}
#endregion
#region URIs
[ThreadStatic]
static private TypeConverter uriConverter;
internal static void SerializeUri(object obj, BinaryTokenStreamWriter stream, Type expected)
{
if (uriConverter == null) uriConverter = TypeDescriptor.GetConverter(typeof(Uri));
stream.Write(uriConverter.ConvertToInvariantString(obj));
}
internal static object DeserializeUri(Type expected, BinaryTokenStreamReader stream)
{
if (uriConverter == null) uriConverter = TypeDescriptor.GetConverter(typeof(Uri));
return uriConverter.ConvertFromInvariantString(stream.ReadString());
}
internal static object CopyUri(object obj)
{
return obj; // URIs are immutable
}
#endregion
#endregion
#region Internal Orleans types
#region Basic types
internal static void SerializeGrainId(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var id = (GrainId) obj;
stream.Write(id);
}
internal static object DeserializeGrainId(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadGrainId();
}
internal static object CopyGrainId(object original)
{
return original;
}
internal static void SerializeActivationId(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var id = (ActivationId)obj;
stream.Write(id);
}
internal static object DeserializeActivationId(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadActivationId();
}
internal static object CopyActivationId(object original)
{
return original;
}
internal static void SerializeActivationAddress(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var addr = (ActivationAddress)obj;
stream.Write(addr);
}
internal static object DeserializeActivationAddress(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadActivationAddress();
}
internal static object CopyActivationAddress(object original)
{
return original;
}
internal static void SerializeIPAddress(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var ip = (IPAddress)obj;
stream.Write(ip);
}
internal static object DeserializeIPAddress(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadIPAddress();
}
internal static object CopyIPAddress(object original)
{
return original;
}
internal static void SerializeIPEndPoint(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var ep = (IPEndPoint)obj;
stream.Write(ep);
}
internal static object DeserializeIPEndPoint(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadIPEndPoint();
}
internal static object CopyIPEndPoint(object original)
{
return original;
}
internal static void SerializeCorrelationId(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var id = (CorrelationId) obj;
stream.Write(id);
}
internal static object DeserializeCorrelationId(Type expected, BinaryTokenStreamReader stream)
{
var bytes = stream.ReadBytes(CorrelationId.SIZE_BYTES);
return new CorrelationId(bytes);
}
internal static object CopyCorrelationId(object original)
{
return original;
}
internal static void SerializeSiloAddress(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var addr = (SiloAddress)obj;
stream.Write(addr);
}
internal static object DeserializeSiloAddress(Type expected, BinaryTokenStreamReader stream)
{
return stream.ReadSiloAddress();
}
internal static object CopySiloAddress(object original)
{
return original;
}
internal static object CopyTaskId(object original)
{
return original;
}
#endregion
#region InvokeMethodRequest
internal static void SerializeInvokeMethodRequest(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var request = (InvokeMethodRequest)obj;
stream.Write(request.InterfaceId);
stream.Write(request.MethodId);
stream.Write(request.Arguments != null ? request.Arguments.Length : 0);
if (request.Arguments != null)
{
foreach (var arg in request.Arguments)
{
SerializationManager.SerializeInner(arg, stream, null);
}
}
}
internal static object DeserializeInvokeMethodRequest(Type expected, BinaryTokenStreamReader stream)
{
int iid = stream.ReadInt();
int mid = stream.ReadInt();
int argCount = stream.ReadInt();
object[] args = null;
if (argCount > 0)
{
args = new object[argCount];
for (var i = 0; i < argCount; i++)
{
args[i] = SerializationManager.DeserializeInner(null, stream);
}
}
return new InvokeMethodRequest(iid, mid, args);
}
internal static object CopyInvokeMethodRequest(object original)
{
var request = (InvokeMethodRequest)original;
object[] args = null;
if (request.Arguments != null)
{
args = new object[request.Arguments.Length];
for (var i = 0; i < request.Arguments.Length; i++)
{
args[i] = SerializationManager.DeepCopyInner(request.Arguments[i]);
}
}
var result = new InvokeMethodRequest(request.InterfaceId, request.MethodId, args);
SerializationContext.Current.RecordObject(original, result);
return result;
}
#endregion
#region Response
internal static void SerializeOrleansResponse(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var resp = (Response)obj;
SerializationManager.SerializeInner(resp.ExceptionFlag ? resp.Exception : resp.Data, stream, null);
}
internal static object DeserializeOrleansResponse(Type expected, BinaryTokenStreamReader stream)
{
var obj = SerializationManager.DeserializeInner(null, stream);
return new Response(obj);
}
internal static object CopyOrleansResponse(object original)
{
var resp = (Response)original;
if (resp.ExceptionFlag)
{
return original;
}
var result = new Response(SerializationManager.DeepCopyInner(resp.Data));
SerializationContext.Current.RecordObject(original, result);
return result;
}
#endregion
#endregion
#region Utilities
private static Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>
RegisterConcreteMethods(Type t, string serializerName, string deserializerName, string copierName, Type[] genericArgs = null)
{
if (genericArgs == null)
{
genericArgs = t.GetGenericArguments();
}
var genericCopier = typeof(BuiltInTypes).GetMethod(copierName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteCopier = genericCopier.MakeGenericMethod(genericArgs);
var copier = (SerializationManager.DeepCopier)concreteCopier.CreateDelegate(typeof(SerializationManager.DeepCopier));
var genericSerializer = typeof(BuiltInTypes).GetMethod(serializerName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteSerializer = genericSerializer.MakeGenericMethod(genericArgs);
var serializer = (SerializationManager.Serializer)concreteSerializer.CreateDelegate(typeof(SerializationManager.Serializer));
var genericDeserializer = typeof(BuiltInTypes).GetMethod(deserializerName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteDeserializer = genericDeserializer.MakeGenericMethod(genericArgs);
var deserializer =
(SerializationManager.Deserializer)concreteDeserializer.CreateDelegate(typeof(SerializationManager.Deserializer));
SerializationManager.Register(t, copier, serializer, deserializer);
return new Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>(serializer, deserializer, copier);
}
public static Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>
RegisterConcreteMethods(Type concreteType, Type definingType, string copierName, string serializerName, string deserializerName, Type[] genericArgs = null)
{
if (genericArgs == null)
{
genericArgs = concreteType.GetGenericArguments();
}
var genericCopier = definingType.GetMethod(copierName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteCopier = genericCopier.MakeGenericMethod(genericArgs);
var copier = (SerializationManager.DeepCopier)concreteCopier.CreateDelegate(typeof(SerializationManager.DeepCopier));
var genericSerializer = definingType.GetMethod(serializerName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteSerializer = genericSerializer.MakeGenericMethod(genericArgs);
var serializer = (SerializationManager.Serializer)concreteSerializer.CreateDelegate(typeof(SerializationManager.Serializer));
var genericDeserializer = definingType.GetMethod(deserializerName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var concreteDeserializer = genericDeserializer.MakeGenericMethod(genericArgs);
var deserializer =
(SerializationManager.Deserializer)concreteDeserializer.CreateDelegate(typeof(SerializationManager.Deserializer));
SerializationManager.Register(concreteType, copier, serializer, deserializer);
return new Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>(serializer, deserializer, copier);
}
#endregion
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Message.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Diagnostics;
using System.Threading;
using Novell.Directory.LDAP.VQ.Rfc2251;
using Novell.Directory.LDAP.VQ.Utilclass;
namespace Novell.Directory.LDAP.VQ
{
/// <summary> Encapsulates an Ldap message, its state, and its replies.</summary>
/* package */
class Message
{
private void InitBlock()
{
replies = new MessageVector(5, 5);
}
/// <summary> Get number of messages queued.
/// Don't count the last message containing result code.
/// </summary>
virtual internal int Count
{
/* package */
get
{
int size = replies.Count;
if (complete)
{
return (size > 0 ? (size - 1) : size);
}
return size;
}
}
/// <summary> sets the agent for this message</summary>
virtual internal MessageAgent Agent
{
/* package */
set
{
agent = value;
}
}
/// <summary> Returns true if replies are queued
///
/// </summary>
/// <returns> false if no replies are queued, otherwise true
/// </returns>
/* package */
internal virtual bool hasReplies()
{
if (replies == null)
{
// abandoned request
return false;
}
return (replies.Count > 0);
}
virtual internal int MessageType
{
/* package */
get
{
if (msg == null)
{
return -1;
}
return msg.Type;
}
}
virtual internal int MessageID
{
/* package */
get
{
return msgId;
}
}
/// <summary> gets the operation complete status for this message
///
/// </summary>
/// <returns> the true if the operation is complete, i.e.
/// the LdapResult has been received.
/// </returns>
virtual internal bool Complete
{
/* package */
get
{
return complete;
}
}
/// <summary> Gets the next reply from the reply queue or waits until one is there
///
/// </summary>
/// <returns> the next reply message on the reply queue or null
/// </returns>
/* package */
internal virtual object waitForReply()
{
if (replies == null)
{
return null;
}
// sync on message so don't confuse with timer thread
lock (replies)
{
object msg = null;
while (waitForReply_Renamed_Field)
{
if ((replies.Count == 0))
{
try
{
Monitor.Wait(replies);
}
catch (Exception ir)
{
// do nothing
}
if (waitForReply_Renamed_Field)
{
continue;
}
break;
}
object temp_object;
temp_object = replies[0];
replies.RemoveAt(0);
msg = temp_object; // Atomic get and remove
if ((complete || !acceptReplies) && (replies.Count == 0))
{
// Remove msg from connection queue when last reply read
conn.removeMessage(this);
}
return msg;
}
return null;
}
}
/// <summary> Gets the next reply from the reply queue if one exists
///
/// </summary>
/// <returns> the next reply message on the reply queue or null if none
/// </returns>
virtual internal object Reply
{
/* package */
get
{
object msg;
if (replies == null)
{
return null;
}
lock (replies)
{
// Test and remove must be atomic
if ((replies.Count == 0))
{
return null; // No data
}
object temp_object;
temp_object = replies[0];
replies.RemoveAt(0);
msg = temp_object; // Atomic get and remove
}
if ((conn != null) && (complete || !acceptReplies) && (replies.Count == 0))
{
// Remove msg from connection queue when last reply read
conn.removeMessage(this);
}
return msg;
}
}
/// <summary> Returns true if replies are accepted for this request.
///
/// </summary>
/// <returns> false if replies are no longer accepted for this request
/// </returns>
/* package */
internal virtual bool acceptsReplies()
{
return acceptReplies;
}
/// <summary> gets the LdapMessage request associated with this message
///
/// </summary>
/// <returns> the LdapMessage request associated with this message
/// </returns>
virtual internal LdapMessage Request
{
/*package*/
get
{
return msg;
}
}
virtual internal bool BindRequest
{
/* package */
get
{
return (bindprops != null);
}
}
/// <summary> gets the MessageAgent associated with this message
///
/// </summary>
/// <returns> the MessageAgent associated with this message
/// </returns>
virtual internal MessageAgent MessageAgent
{
/* package */
get
{
return agent;
}
}
private LdapMessage msg; // msg request sent to server
private Connection conn; // Connection object where msg sent
private MessageAgent agent; // MessageAgent handling this request
private LdapMessageQueue queue; // Application message queue
private int mslimit; // client time limit in milliseconds
private SupportClass.TaskClass timer = null; // Timeout thread
// Note: MessageVector is synchronized
private MessageVector replies; // place to store replies
private int msgId; // message ID of this request
private bool acceptReplies = true; // false if no longer accepting replies
private bool waitForReply_Renamed_Field = true; // true if wait for reply
private bool complete = false; // true LdapResult received
private string name; // String name used for Debug
private BindProperties bindprops; // Bind properties if a bind request
internal Message(LdapMessage msg, int mslimit, Connection conn, MessageAgent agent, LdapMessageQueue queue, BindProperties bindprops)
{
InitBlock();
this.msg = msg;
this.conn = conn;
this.agent = agent;
this.queue = queue;
this.mslimit = mslimit;
msgId = msg.MessageID;
this.bindprops = bindprops;
}
internal void sendMessage()
{
conn.writeMessage(this);
// Start the timer thread
if (mslimit != 0)
{
// Don't start the timer thread for abandon or Unbind
switch (msg.Type)
{
case LdapMessage.ABANDON_REQUEST:
case LdapMessage.UNBIND_REQUEST:
mslimit = 0;
break;
default:
timer = new Timeout(this, mslimit, this);
//timer.IsBackground = true; // If this is the last thread running, allow exit.
timer.Start();
break;
}
}
}
internal virtual void Abandon(LdapConstraints cons, InterThreadException informUserEx)
{
if (!waitForReply_Renamed_Field)
{
return;
}
acceptReplies = false; // don't listen to anyone
waitForReply_Renamed_Field = false; // don't let sleeping threads lie
if (!complete)
{
try
{
// If a bind, release bind semaphore & wake up waiting threads
// Must do before writing abandon message, otherwise deadlock
if (bindprops != null)
{
int id;
if (conn.BindSemIdClear)
{
// Semaphore id for normal operations
id = msgId;
}
else
{
// Semaphore id for sasl bind
id = conn.BindSemId;
conn.clearBindSemId();
}
conn.freeWriteSemaphore(id);
}
// Create the abandon message, but don't track it.
LdapControl[] cont = null;
if (cons != null)
{
cont = cons.getControls();
}
LdapMessage msg = new LdapAbandonRequest(msgId, cont);
// Send abandon message to server
conn.writeMessage(msg);
}
catch (LdapException ex)
{
// do nothing
}
// If not informing user, remove message from agent
if (informUserEx == null)
{
agent.Abandon(msgId, null);
}
conn.removeMessage(this);
}
// Get rid of all replies queued
if (informUserEx != null)
{
replies.Add(new LdapResponse(informUserEx, conn.ActiveReferral));
stopTimer();
// wake up waiting threads to receive exception
sleepersAwake();
// Message will get cleaned up when last response removed from queue
}
else
{
// Wake up any waiting threads, so they can terminate.
// If informing the user, we wake sleepers after
// caller queues dummy response with error status
sleepersAwake();
cleanup();
}
}
private void cleanup()
{
stopTimer(); // Make sure timer stopped
try
{
acceptReplies = false;
conn?.removeMessage(this);
// Empty out any accumuluated replies
if (replies != null)
{
while (replies.Count != 0)
{
var temp_object = replies[0];
replies.RemoveAt(0);
object generatedAux = temp_object;
}
}
}
catch (Exception ex)
{
// nothing
}
// Let GC clean up this stuff, leave name in case finalized is called
conn = null;
msg = null;
// agent = null; // leave this reference
queue = null;
//replies = null; //leave this since we use it as a semaphore
bindprops = null;
}
~Message()
{
cleanup();
}
internal virtual void putReply(RfcLdapMessage message)
{
if (!acceptReplies)
{
return;
}
lock (replies)
{
replies.Add(message);
}
message.RequestingMessage = msg; // Save request message info
switch (message.Type)
{
case LdapMessage.SEARCH_RESPONSE:
case LdapMessage.SEARCH_RESULT_REFERENCE:
case LdapMessage.INTERMEDIATE_RESPONSE:
break;
default:
int res;
stopTimer();
// Accept no more results for this message
// Leave on connection queue so we can abandon if necessary
acceptReplies = false;
complete = true;
if (bindprops != null)
{
res = ((RfcResponse)message.Response).getResultCode().intValue();
if (res == LdapException.SASL_BIND_IN_PROGRESS)
{
}
else
{
// We either have success or failure on the bind
if (res == LdapException.SUCCESS)
{
// Set bind properties into connection object
conn.BindProperties = bindprops;
}
// If not a sasl bind in-progress, release the bind
// semaphore and wake up all waiting threads
int id;
if (conn.BindSemIdClear)
{
// Semaphore id for normal operations
id = msgId;
}
else
{
// Semaphore id for sasl bind
id = conn.BindSemId;
conn.clearBindSemId();
}
conn.freeWriteSemaphore(id);
}
}
break;
}
// wake up waiting threads
sleepersAwake();
}
/// <summary> stops the timeout timer from running</summary>
/* package */
internal virtual void stopTimer()
{
// If timer thread started, stop it
timer?.Interrupt();
}
/// <summary> Notifies all waiting threads</summary>
private void sleepersAwake()
{
// Notify any thread waiting for this message id
lock (replies)
{
Monitor.Pulse(replies);
}
// Notify a thread waiting for any message id
agent.sleepersAwake(false);
}
/// <summary> Timer class to provide timing for messages. Only called
/// if time to wait is non zero.
/// </summary>
private sealed class Timeout : SupportClass.TaskClass
{
private int timeToWait = 0;
private Message message;
/* package */
internal Timeout(Message enclosingInstance, int interval, Message msg) : base()
{
timeToWait = interval;
message = msg;
}
/// <summary> The timeout thread. If it wakes from the sleep, future input
/// is stopped and the request is timed out.
/// </summary>
override public void Run()
{
try
{
ThrowIfCancellationRequested();
Thread.Sleep(new TimeSpan(10000 * timeToWait));
ThrowIfCancellationRequested();
message.acceptReplies = false;
// Note: Abandon clears the bind semaphore after failed bind.
message.Abandon(null,
new InterThreadException("Client request timed out", null, LdapException.Ldap_TIMEOUT, null, message));
}
catch (OperationCanceledException oce)
{
Debug.WriteLine("Timer was stopped by cancellation token");
}
catch (Exception ie)
{
// the timer was stopped, do nothing
}
}
}
/// <summary> sets the agent for this message</summary>
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security.Permissions
{
using System;
using System.Security.Util;
using System.IO;
using String = System.String;
using Version = System.Version;
using System.Security.Policy;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
// The only difference between this class and System.Security.Policy.StrongName is that this one
// allows m_name to be null. We should merge this class with System.Security.Policy.StrongName
[Serializable]
sealed internal class StrongName2
{
public StrongNamePublicKeyBlob m_publicKeyBlob;
public String m_name;
public Version m_version;
public StrongName2(StrongNamePublicKeyBlob publicKeyBlob, String name, Version version)
{
m_publicKeyBlob = publicKeyBlob;
m_name = name;
m_version = version;
}
public StrongName2 Copy()
{
return new StrongName2(m_publicKeyBlob, m_name, m_version);
}
public bool IsSubsetOf(StrongName2 target)
{
// This StrongName2 is a subset of the target if it's public key blob is null no matter what
if (this.m_publicKeyBlob == null)
return true;
// Subsets are always false if the public key blobs do not match
if (!this.m_publicKeyBlob.Equals( target.m_publicKeyBlob ))
return false;
// We use null in strings to represent the "Anything" state.
// Therefore, the logic to detect an individual subset is:
//
// 1. If the this string is null ("Anything" is a subset of any other).
// 2. If the this string and target string are the same (equality is sufficient for a subset).
//
// The logic is reversed here to discover things that are not subsets.
if (this.m_name != null)
{
if (target.m_name == null || !System.Security.Policy.StrongName.CompareNames( target.m_name, this.m_name ))
return false;
}
if ((Object) this.m_version != null)
{
if ((Object) target.m_version == null ||
target.m_version.CompareTo( this.m_version ) != 0)
{
return false;
}
}
return true;
}
public StrongName2 Intersect(StrongName2 target)
{
if (target.IsSubsetOf( this ))
return target.Copy();
else if (this.IsSubsetOf( target ))
return this.Copy();
else
return null;
}
public bool Equals(StrongName2 target)
{
if (!target.IsSubsetOf(this))
return false;
if (!this.IsSubsetOf(target))
return false;
return true;
}
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class StrongNameIdentityPermission : CodeAccessPermission, IBuiltInPermission
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
private bool m_unrestricted;
private StrongName2[] m_strongNames;
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public StrongNameIdentityPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_unrestricted = true;
}
else if (state == PermissionState.None)
{
m_unrestricted = false;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version )
{
if (blob == null)
throw new ArgumentNullException( nameof(blob) );
if (name != null && name.Equals( "" ))
throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) );
Contract.EndContractBlock();
m_unrestricted = false;
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(blob, name, version);
}
//------------------------------------------------------
//
// PUBLIC ACCESSOR METHODS
//
//------------------------------------------------------
public StrongNamePublicKeyBlob PublicKey
{
set
{
if (value == null)
throw new ArgumentNullException( nameof(PublicKey) );
Contract.EndContractBlock();
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_publicKeyBlob = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(value, "", new Version());
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return null;
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_publicKeyBlob;
}
}
public String Name
{
set
{
if (value != null && value.Length == 0)
throw new ArgumentException( Environment.GetResourceString("Argument_EmptyName" ));
Contract.EndContractBlock();
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_name = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(null, value, new Version());
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return "";
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_name;
}
}
public Version Version
{
set
{
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_version = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(null, "", value);
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return new Version();
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_version;
}
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
//
//------------------------------------------------------
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override IPermission Copy()
{
StrongNameIdentityPermission perm = new StrongNameIdentityPermission(PermissionState.None);
perm.m_unrestricted = this.m_unrestricted;
if(this.m_strongNames != null)
{
perm.m_strongNames = new StrongName2[this.m_strongNames.Length];
int n;
for(n = 0; n < this.m_strongNames.Length; n++)
perm.m_strongNames[n] = this.m_strongNames[n].Copy();
}
return perm;
}
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
if(m_unrestricted)
return false;
if(m_strongNames == null)
return true;
if(m_strongNames.Length == 0)
return true;
return false;
}
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(that.m_unrestricted)
return true;
if(m_unrestricted)
return false;
if(this.m_strongNames != null)
{
foreach(StrongName2 snThis in m_strongNames)
{
bool bOK = false;
if(that.m_strongNames != null)
{
foreach(StrongName2 snThat in that.m_strongNames)
{
if(snThis.IsSubsetOf(snThat))
{
bOK = true;
break;
}
}
}
if(!bOK)
return false;
}
}
return true;
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
return null;
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(this.m_unrestricted && that.m_unrestricted)
{
StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
res.m_unrestricted = true;
return res;
}
if(this.m_unrestricted)
return that.Copy();
if(that.m_unrestricted)
return this.Copy();
if(this.m_strongNames == null || that.m_strongNames == null || this.m_strongNames.Length == 0 || that.m_strongNames.Length == 0)
return null;
List<StrongName2> alStrongNames = new List<StrongName2>();
foreach(StrongName2 snThis in this.m_strongNames)
{
foreach(StrongName2 snThat in that.m_strongNames)
{
StrongName2 snInt = (StrongName2)snThis.Intersect(snThat);
if(snInt != null)
alStrongNames.Add(snInt);
}
}
if(alStrongNames.Count == 0)
return null;
StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
result.m_strongNames = alStrongNames.ToArray();
return result;
}
public override IPermission Union(IPermission target)
{
if (target == null)
{
if((this.m_strongNames == null || this.m_strongNames.Length == 0) && !this.m_unrestricted)
return null;
return this.Copy();
}
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(this.m_unrestricted || that.m_unrestricted)
{
StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
res.m_unrestricted = true;
return res;
}
if (this.m_strongNames == null || this.m_strongNames.Length == 0)
{
if(that.m_strongNames == null || that.m_strongNames.Length == 0)
return null;
return that.Copy();
}
if(that.m_strongNames == null || that.m_strongNames.Length == 0)
return this.Copy();
List<StrongName2> alStrongNames = new List<StrongName2>();
foreach(StrongName2 snThis in this.m_strongNames)
alStrongNames.Add(snThis);
foreach(StrongName2 snThat in that.m_strongNames)
{
bool bDupe = false;
foreach(StrongName2 sn in alStrongNames)
{
if(snThat.Equals(sn))
{
bDupe = true;
break;
}
}
if(!bDupe)
alStrongNames.Add(snThat);
}
StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
result.m_strongNames = alStrongNames.ToArray();
return result;
}
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return StrongNameIdentityPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.StrongNameIdentityPermissionIndex;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2017 by Rob Jellinghaus. //
// Licensed under MIT license, http://github.com/RobJellinghaus/Touchofunk //
/////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
namespace Holofunk.Core
{
/// <summary>
/// Sample identifies Times based on audio sample counts.
/// </summary>
public class Sample
{
}
/// <summary>
/// Frame identifies Times based on video frame counts.
/// </summary>
public class Frame
{
}
/// <summary>
/// Time parameterized on some underlying measurement.
/// </summary>
public struct Time<TTime>
{
readonly long _time;
public Time(long time)
{
_time = time;
}
public override string ToString()
{
return "T[" + (long)this + "]";
}
public override bool Equals(object obj)
{
if (!(obj is Time<TTime>))
{
return false;
}
return this == (Time<TTime>)obj;
}
public override int GetHashCode()
{
return _time.GetHashCode();
}
public static Time<TTime> Min(Time<TTime> first, Time<TTime> second)
{
return new Time<TTime>(Math.Min(first, second));
}
public static Time<TTime> Max(Time<TTime> first, Time<TTime> second)
{
return new Time<TTime>(Math.Max(first, second));
}
public static implicit operator long(Time<TTime> time)
{
return time._time;
}
public static implicit operator Time<TTime>(long time)
{
return new Time<TTime>(time);
}
public static bool operator <(Time<TTime> first, Time<TTime> second)
{
return (long)first < (long)second;
}
public static bool operator >(Time<TTime> first, Time<TTime> second)
{
return (long)first > (long)second;
}
public static bool operator ==(Time<TTime> first, Time<TTime> second)
{
return (long)first == (long)second;
}
public static bool operator !=(Time<TTime> first, Time<TTime> second)
{
return (long)first != (long)second;
}
public static bool operator <=(Time<TTime> first, Time<TTime> second)
{
return (long)first <= (long)second;
}
public static bool operator >=(Time<TTime> first, Time<TTime> second)
{
return (long)first >= (long)second;
}
public static Duration<TTime> operator -(Time<TTime> first, Time<TTime> second)
{
return new Duration<TTime>((long)first - (long)second);
}
public static Time<TTime> operator -(Time<TTime> first, Duration<TTime> second)
{
return new Time<TTime>((long)first - (long)second);
}
}
/// <summary>
/// A distance between two Times.
/// </summary>
/// <typeparam name="TTime"></typeparam>
public struct Duration<TTime>
{
readonly long _count;
public Duration(long count)
{
HoloDebug.Assert(count >= 0);
_count = count;
}
public override string ToString()
{
return "D[" + (long)this + "]";
}
public static implicit operator long(Duration<TTime> offset)
{
return offset._count;
}
public static implicit operator Duration<TTime>(long value)
{
return new Duration<TTime>(value);
}
public override bool Equals(object obj)
{
if (!(obj is Duration<TTime>))
{
return false;
}
return this == (Duration<TTime>)obj;
}
public override int GetHashCode()
{
return _count.GetHashCode();
}
public static Duration<TTime> Min(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>(Math.Min(first, second));
}
public static Duration<TTime> operator +(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>((long)first + (long)second);
}
public static Duration<TTime> operator -(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>((long)first - (long)second);
}
public static Duration<TTime> operator /(Duration<TTime> first, int second)
{
return new Duration<TTime>((long)first / second);
}
public static bool operator <(Duration<TTime> first, Duration<TTime> second)
{
return (long)first < (long)second;
}
public static bool operator >(Duration<TTime> first, Duration<TTime> second)
{
return (long)first > (long)second;
}
public static bool operator <=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first <= (long)second;
}
public static bool operator >=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first >= (long)second;
}
public static bool operator ==(Duration<TTime> first, Duration<TTime> second)
{
return (long)first == (long)second;
}
public static bool operator !=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first != (long)second;
}
public static Time<TTime> operator +(Time<TTime> first, Duration<TTime> second)
{
return new Time<TTime>((long)first + (long)second);
}
}
/// <summary>
/// An interval, defined as a start time and a duration (aka length).
/// </summary>
/// <remarks>
/// Empty intervals semantically have no InitialTime, and no distinction should be made between empty
/// intervals based on InitialTime.</remarks>
/// <typeparam name="TTime"></typeparam>
public struct Interval<TTime>
{
public readonly Time<TTime> InitialTime;
public readonly Duration<TTime> Duration;
readonly bool _isInitialized;
public Interval(Time<TTime> initialTime, Duration<TTime> duration)
{
HoloDebug.Assert(duration >= 0);
InitialTime = initialTime;
Duration = duration;
_isInitialized = true;
}
public override string ToString()
{
return "I[" + InitialTime + ", " + Duration + "]";
}
public static Interval<TTime> Empty { get { return new Interval<TTime>(0, 0); } }
public bool IsInitialized { get { return _isInitialized; } }
public bool IsEmpty
{
get { return Duration == 0; }
}
public Interval<TTime> SubintervalStartingAt(Duration<TTime> offset)
{
Debug.Assert(offset <= Duration);
return new Interval<TTime>(InitialTime + offset, Duration - offset);
}
public Interval<TTime> SubintervalOfDuration(Duration<TTime> duration)
{
Debug.Assert(duration <= Duration);
return new Interval<TTime>(InitialTime, duration);
}
public Interval<TTime> Intersect(Interval<TTime> other)
{
Time<TTime> intersectionStart = Time<TTime>.Max(InitialTime, other.InitialTime);
Time<TTime> intersectionEnd = Time<TTime>.Min(InitialTime + Duration, other.InitialTime + other.Duration);
if (intersectionEnd < intersectionStart) {
return Interval<TTime>.Empty;
}
else {
return new Interval<TTime>(intersectionStart, intersectionEnd - intersectionStart);
}
}
public bool Contains(Time<TTime> time)
{
if (IsEmpty) {
return false;
}
return InitialTime <= time
&& (InitialTime + Duration) > time;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Find_Fest_API.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OrchardCore.Environment.Extensions;
using OrchardCore.Environment.Extensions.Features;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Builders;
using OrchardCore.Environment.Shell.Builders.Models;
using OrchardCore.Environment.Shell.Descriptor.Models;
using OrchardCore.Modules;
using OrchardCore.Tests.Stubs;
using Xunit;
namespace OrchardCore.Tests.Shell
{
public class ShellContainerFactoryTests
{
private readonly IShellContainerFactory _shellContainerFactory;
private readonly IServiceProvider _applicationServiceProvider;
public ShellContainerFactoryTests()
{
var applicationServices = new ServiceCollection();
applicationServices.AddSingleton<ITypeFeatureProvider, TypeFeatureProvider>();
applicationServices.AddSingleton<ITestSingleton, TestSingleton>();
applicationServices.AddTransient<ITestTransient, TestTransient>();
applicationServices.AddScoped<ITestScoped, TestScoped>();
applicationServices.AddSingleton<ITwoHostSingletonsOfTheSameType, FirstHostSingletonsOfTheSameType>();
applicationServices.AddSingleton<ITwoHostSingletonsOfTheSameType, SecondHostSingletonsOfTheSameType>();
applicationServices.AddSingleton<IHostSingletonAndScopedOfTheSameType, HostSingletonOfTheSameTypeAsScoped>();
applicationServices.AddScoped<IHostSingletonAndScopedOfTheSameType, HostScopedOfTheSameTypeAsSingleton>();
_shellContainerFactory = new ShellContainerFactory(
new StubHostingEnvironment(),
new StubExtensionManager(),
_applicationServiceProvider = applicationServices.BuildServiceProvider(),
applicationServices
);
}
[Fact]
public void CanRegisterDefaultServiceWithFeatureInfo()
{
var shellBlueprint = CreateBlueprint();
var expectedFeatureInfo = AddStartup(shellBlueprint, typeof(RegisterServiceStartup));
var container = _shellContainerFactory.CreateContainer(ShellHelper.BuildDefaultUninitializedShell, shellBlueprint).CreateScope().ServiceProvider;
var typeFeatureProvider = _applicationServiceProvider.GetService<ITypeFeatureProvider>();
Assert.IsType<TestService>(container.GetRequiredService(typeof(ITestService)));
Assert.Same(expectedFeatureInfo, typeFeatureProvider.GetFeatureForDependency(typeof(TestService)));
}
[Fact]
public void CanReplaceDefaultServiceWithCustomService()
{
var shellBlueprint = CreateBlueprint();
var expectedFeatureInfo = AddStartup(shellBlueprint, typeof(ReplaceServiceStartup));
AddStartup(shellBlueprint, typeof(RegisterServiceStartup));
var container = _shellContainerFactory.CreateContainer(ShellHelper.BuildDefaultUninitializedShell, shellBlueprint).CreateScope().ServiceProvider;
var typeFeatureProvider = _applicationServiceProvider.GetService<ITypeFeatureProvider>();
// Check that the default service has been replaced with the custom service and that the feature info is correct.
Assert.IsType<CustomTestService>(container.GetRequiredService(typeof(ITestService)));
Assert.Same(expectedFeatureInfo, typeFeatureProvider.GetFeatureForDependency(typeof(CustomTestService)));
}
[Fact]
public void HostServiceLifeTimesShouldBePreserved()
{
var shellBlueprint = CreateBlueprint();
var container = _shellContainerFactory.CreateContainer(ShellHelper.BuildDefaultUninitializedShell, shellBlueprint).CreateScope().ServiceProvider;
var singleton1 = container.GetRequiredService<ITestSingleton>();
var singleton2 = container.GetRequiredService<ITestSingleton>();
var transient1 = container.GetRequiredService<ITestTransient>();
var transient2 = container.GetRequiredService<ITestTransient>();
var scoped1 = container.GetRequiredService<ITestScoped>();
var scoped2 = container.GetRequiredService<ITestScoped>();
ITestScoped scoped3, scoped4;
using (var scope = container.CreateScope())
{
scoped3 = scope.ServiceProvider.GetRequiredService<ITestScoped>();
scoped4 = scope.ServiceProvider.GetRequiredService<ITestScoped>();
}
Assert.IsType<TestSingleton>(singleton1);
Assert.IsType<TestTransient>(transient1);
Assert.IsType<TestTransient>(transient2);
Assert.IsType<TestScoped>(scoped1);
Assert.IsType<TestScoped>(scoped3);
Assert.Equal(singleton1, singleton2);
Assert.NotEqual(transient1, transient2);
Assert.NotEqual(scoped1, scoped3);
Assert.Equal(scoped1, scoped2);
Assert.Equal(scoped3, scoped4);
}
[Fact]
public void WhenTwoHostSingletons_GetServices_Returns_HostAndShellServices()
{
var shellBlueprint = CreateBlueprint();
AddStartup(shellBlueprint, typeof(ServicesOfTheSameTypeStartup));
var container = _shellContainerFactory.CreateContainer(ShellHelper.BuildDefaultUninitializedShell, shellBlueprint).CreateScope().ServiceProvider;
var services = container.GetServices<ITwoHostSingletonsOfTheSameType>();
Assert.Equal(5, services.Count());
}
[Fact]
public void WhenHostSingletonAndScoped_GetServices_Returns_CorrectImplementations()
{
var shellBlueprint = CreateBlueprint();
var container = _shellContainerFactory.CreateContainer(ShellHelper.BuildDefaultUninitializedShell, shellBlueprint).CreateScope().ServiceProvider;
var services = container.GetServices<IHostSingletonAndScopedOfTheSameType>();
Assert.Equal(2, services.Count());
Assert.IsType<HostSingletonOfTheSameTypeAsScoped>(services.ElementAt(0));
Assert.IsType<HostScopedOfTheSameTypeAsSingleton>(services.ElementAt(1));
}
private ShellBlueprint CreateBlueprint()
{
return new ShellBlueprint
{
Settings = new ShellSettings(),
Descriptor = new ShellDescriptor(),
Dependencies = new Dictionary<Type, FeatureEntry>()
};
}
public static IFeatureInfo AddStartup(ShellBlueprint shellBlueprint, Type startupType)
{
var featureInfo = new FeatureInfo(startupType.Name, startupType.Name, 1, "Tests", null, null, null, false, false);
shellBlueprint.Dependencies.Add(startupType, new FeatureEntry(featureInfo));
return featureInfo;
}
private interface ITestService
{
}
private class TestService : ITestService
{
}
private class CustomTestService : ITestService
{
}
private class RegisterServiceStartup : StartupBase
{
public override int Order => 1;
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ITestService, TestService>();
}
}
private class ReplaceServiceStartup : StartupBase
{
public override int Order => 2;
public override void ConfigureServices(IServiceCollection services)
{
services.Replace(ServiceDescriptor.Scoped(typeof(ITestService), typeof(CustomTestService)));
}
}
private interface ITestSingleton { }
private interface ITestTransient { }
private interface ITestScoped { }
private class TestSingleton : ITestSingleton { }
private class TestTransient : ITestTransient { }
private class TestScoped : ITestScoped { }
private interface ITwoHostSingletonsOfTheSameType { }
private class FirstHostSingletonsOfTheSameType : ITwoHostSingletonsOfTheSameType { }
private class SecondHostSingletonsOfTheSameType : ITwoHostSingletonsOfTheSameType { }
private class ShellSingletonOfTheSametype : ITwoHostSingletonsOfTheSameType { }
private class ShellTransientOfTheSametype : ITwoHostSingletonsOfTheSameType { }
private class ShellScopedOfTheSametype : ITwoHostSingletonsOfTheSameType { }
private interface IHostSingletonAndScopedOfTheSameType { }
private class HostSingletonOfTheSameTypeAsScoped : IHostSingletonAndScopedOfTheSameType { }
private class HostScopedOfTheSameTypeAsSingleton : IHostSingletonAndScopedOfTheSameType { }
private class ServicesOfTheSameTypeStartup : StartupBase
{
public override int Order => 1;
public override void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITwoHostSingletonsOfTheSameType, ShellSingletonOfTheSametype>();
services.AddTransient<ITwoHostSingletonsOfTheSameType, ShellTransientOfTheSametype>();
services.AddScoped<ITwoHostSingletonsOfTheSameType, ShellScopedOfTheSametype>();
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Login.cs" company="The Watcher">
// Copyright (c) The Watcher Partial Rights Reserved.
// This software is licensed under the MIT license. See license.txt for details.
// </copyright>
// <summary>
// Code Named: PG-Ripper
// Function : Extracts Images posted on VB forums and attempts to fetch them to disk.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Ripper
{
using System;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Timers;
using System.Windows.Forms;
using Ripper.Core.Components;
using Ripper.Core.Objects;
/// <summary>
/// The Login Dialog
/// </summary>
public partial class Login : Form
{
/// <summary>
/// The Resource Manger Instance
/// </summary>
private ResourceManager rm;
/// <summary>
/// Initializes a new instance of the <see cref="Login"/> class.
/// </summary>
public Login()
{
this.InitializeComponent();
}
/// <summary>
/// Set Language Strings
/// </summary>
private void AdjustCulture()
{
this.groupBox1.Text = this.rm.GetString("gbLoginHead");
this.label1.Text = this.rm.GetString("lblUser");
this.label2.Text = this.rm.GetString("lblPass");
this.LoginButton.Text = this.rm.GetString("logintext");
this.label5.Text = this.rm.GetString("gbLanguage");
this.label6.Text = this.rm.GetString("lblForums");
this.GuestLogin.Text = this.rm.GetString("GuestLogin");
}
/// <summary>
/// Loads the Form
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void LoginLoad(object sender, EventArgs e)
{
// Set Default Forum
this.ForumList.SelectedIndex = 0;
// Load Language Setting
try
{
var language = CacheController.Instance().UserSettings.Language;
switch (language)
{
case "de-DE":
this.LanuageSelector.SelectedIndex = 0;
break;
case "fr-FR":
this.LanuageSelector.SelectedIndex = 1;
break;
case "en-EN":
this.LanuageSelector.SelectedIndex = 2;
break;
default:
this.LanuageSelector.SelectedIndex = 2;
break;
}
}
catch (Exception)
{
this.LanuageSelector.SelectedIndex = 2;
}
}
/// <summary>
/// Tries to Login to the Forums
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void LoginBtnClick(object sender, EventArgs e)
{
if (this.ForumUrl.Text.StartsWith("http://"))
{
if (!this.ForumUrl.Text.EndsWith("/"))
{
this.ForumUrl.Text += "/";
}
CacheController.Instance().UserSettings.CurrentForumUrl = this.ForumUrl.Text;
}
string welcomeString = this.rm.GetString("lblWelcome"), lblFailed = this.rm.GetString("lblFailed");
if (this.GuestLogin.Checked)
{
this.UserNameField.Text = "Guest";
this.PasswordField.Text = "Guest";
this.label3.Text = string.Format("{0}{1}", welcomeString, this.UserNameField.Text);
this.label3.ForeColor = Color.Green;
this.LoginButton.Enabled = false;
if (
CacheController.Instance().UserSettings.ForumsAccount.Any(
item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl))
{
CacheController.Instance().UserSettings.ForumsAccount.RemoveAll(
item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl);
}
var forumsAccount = new ForumAccount
{
ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl,
UserName = this.UserNameField.Text,
UserPassWord = this.PasswordField.Text,
GuestAccount = false
};
CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount);
CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text;
this.timer1.Enabled = true;
}
else
{
// Encrypt Password
this.PasswordField.Text =
Utility.EncodePassword(this.PasswordField.Text).Replace("-", string.Empty).ToLower();
var loginManager = new LoginManager(this.UserNameField.Text, this.PasswordField.Text);
if (loginManager.DoLogin(CacheController.Instance().UserSettings.CurrentForumUrl))
{
this.label3.Text = string.Format("{0}{1}", welcomeString, this.UserNameField.Text);
this.label3.ForeColor = Color.Green;
this.LoginButton.Enabled = false;
if (
CacheController.Instance().UserSettings.ForumsAccount.Any(
item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl))
{
CacheController.Instance().UserSettings.ForumsAccount.RemoveAll(
item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl);
}
var forumsAccount = new ForumAccount
{
ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl,
UserName = this.UserNameField.Text,
UserPassWord = this.PasswordField.Text,
GuestAccount = false
};
CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount);
CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text;
this.timer1.Enabled = true;
}
else
{
this.label3.Text = lblFailed;
this.label3.ForeColor = Color.Red;
}
}
}
/// <summary>
/// If Login successfully send user data to MainForm
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param>
private void Timer1Elapsed(object sender, ElapsedEventArgs e)
{
this.timer1.Enabled = false;
((MainForm)this.Owner).cameThroughCorrectLogin = true;
if (CacheController.Instance().UserSettings.ForumsAccount.Any(item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl))
{
CacheController.Instance().UserSettings.ForumsAccount.RemoveAll(
item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl);
}
var forumsAccount = new ForumAccount
{
ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl,
UserName = this.UserNameField.Text,
UserPassWord = this.PasswordField.Text,
GuestAccount = this.GuestLogin.Checked
};
CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount);
CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text;
this.Close();
}
/// <summary>
/// Changes the UI Language based on the selected Language
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void LanuageSelectorIndexChanged(object sender, EventArgs e)
{
switch (this.LanuageSelector.SelectedIndex)
{
case 0:
this.rm = new ResourceManager("Ripper.Languages.german", Assembly.GetExecutingAssembly());
CacheController.Instance().UserSettings.Language = "de-DE";
break;
case 1:
this.rm = new ResourceManager("Ripper.Languages.french", Assembly.GetExecutingAssembly());
CacheController.Instance().UserSettings.Language = "fr-FR";
break;
case 2:
this.rm = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly());
CacheController.Instance().UserSettings.Language = "en-EN";
break;
default:
this.rm = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly());
CacheController.Instance().UserSettings.Language = "en-EN";
break;
}
this.AdjustCulture();
}
/// <summary>
/// Forum Chooser
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void ForumSelectedIndexChanged(object sender, EventArgs e)
{
switch (this.ForumList.SelectedIndex)
{
case 2:
this.ForumUrl.Text = "https://vipergirls.to/";
break;
case 3:
this.ForumUrl.Text = "http://forums.sexyandfunny.com/";
break;
case 4:
this.ForumUrl.Text = "http://forum.scanlover.com/";
break;
case 5:
this.ForumUrl.Text = "http://bignaturalsonly.com/";
break;
case 6:
this.ForumUrl.Text = "http://forum.phun.org/";
break;
case 7:
this.ForumUrl.Text = "http://...";
break;
default:
this.ForumUrl.Text = "http://...";
break;
}
}
/// <summary>
/// Handles the CheckedChanged event of the GuestLogin control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void GuestLogin_CheckedChanged(object sender, EventArgs e)
{
this.UserNameField.Enabled = !this.GuestLogin.Checked;
this.PasswordField.Enabled = !this.GuestLogin.Checked;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
/**
* INSTRUCTIONS
*
* - Only modify properties in the USER SETTINGS region.
* - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates!
*/
/**
* Used to pop up the window on import.
*/
public class pb_AboutWindowSetup : AssetPostprocessor
{
#region Initialization
static void OnPostprocessAllAssets (
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
string[] entries = System.Array.FindAll(importedAssets, name => name.Contains("pc_AboutEntry") && !name.EndsWith(".meta"));
foreach(string str in entries)
if( pb_AboutWindow.Init(str, false) )
break;
}
#endregion
}
public class pb_AboutWindow : EditorWindow
{
/**
* Modify these constants to customize about screen.
*/
#region User Settings
const string PACKAGE_NAME = "ProBuilder";
/* Path to the root folder */
const string ABOUT_ROOT = "Assets/ProCore/" + PACKAGE_NAME + "/About";
/**
* Changelog.txt file should follow this format:
*
* | -- Product Name 2.1.0 -
* |
* | # Features
* | - All kinds of awesome stuff
* | - New flux capacitor design achieves time travel at lower velocities.
* | - Dark matter reactor recalibrated.
* |
* | # Bug Fixes
* | - No longer explodes when spacebar is pressed.
* | - Fix rolling issue in Rickmeter.
* |
* | # Changes
* | - Changed Blue to Red.
* | - Enter key now causes explosions.
*
* This path is relative to the PRODUCT_ROOT path.
*
* Note that your changelog may contain multiple entries. Only the top-most
* entry will be displayed.
*/
/**
* Advertisement thumb constructor is:
* new AdvertisementThumb( PathToAdImage : string, URLToPurchase : string, ProductDescription : string )
* Provide as many or few (or none) as desired.
*
* Notes - The http:// part is required. Partial URLs do not work on Mac.
*/
[SerializeField]
public static AdvertisementThumb[] advertisements = new AdvertisementThumb[] {
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProBuilder_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/probuilder/", "Build and Texture Geometry In-Editor"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGrids_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progrids/", "True Grids and Grid-Snapping"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGroups_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progroups/", "Hide, Freeze, Group, & Organize"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/Prototype_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/prototype/", "Design and Build With Zero Lag"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickBrush_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickbrush/", "Quickly Add Detail Geometry"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickDecals_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickdecals/", "Add Dirt, Splatters, Posters, etc"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickEdit_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickedit/", "Edit Imported Meshes!"),
};
#endregion
/* Recommend you do not modify these. */
#region Private Fields (automatically populated)
private string AboutEntryPath = "";
private string ProductName = "";
// private string ProductIdentifer = "";
private string ProductVersion = "";
private string ChangelogPath = "";
private string BannerPath = ABOUT_ROOT + "/Images/Banner.png";
const int AD_HEIGHT = 96;
/**
* Struct containing data for use in Advertisement shelf.
*/
[System.Serializable]
public struct AdvertisementThumb
{
public Texture2D image;
public string url;
public string about;
public GUIContent guiContent;
public AdvertisementThumb(string imagePath, string url, string about)
{
guiContent = new GUIContent("", about);
this.image = LoadAssetAtPath<Texture2D>(imagePath);
guiContent.image = this.image;
this.url = url;
this.about = about;
}
}
Texture2D banner;
// populated by first entry in changelog
string changelog = "";
#endregion
#region Init
/**
* Return true if Init took place, false if not.
*/
public static bool Init (string aboutEntryPath, bool fromMenu)
{
string identifier, version;
if( !GetField(aboutEntryPath, "version: ", out version) || !GetField(aboutEntryPath, "identifier: ", out identifier))
return false;
if(fromMenu || EditorPrefs.GetString(identifier) != version)
{
string tname;
pb_AboutWindow win;
if(GetField(aboutEntryPath, "name: ", out tname))
win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow), true, tname, true);
else
win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow));
win.SetAboutEntryPath(aboutEntryPath);
win.ShowUtility();
EditorPrefs.SetString(identifier, version);
return true;
}
else
{
return false;
}
}
public void OnEnable()
{
banner = LoadAssetAtPath<Texture2D>(BannerPath);
// With Unity 4 (on PC) if you have different values for minSize and maxSize,
// they do not apply restrictions to window size.
#if !UNITY_5
this.minSize = new Vector2(banner.width + 12, banner.height * 7);
this.maxSize = new Vector2(banner.width + 12, banner.height * 7);
#else
this.minSize = new Vector2(banner.width + 12, banner.height * 6);
this.maxSize = new Vector2(banner.width + 12, 1440);
#endif
}
public void SetAboutEntryPath(string path)
{
AboutEntryPath = path;
PopulateDataFields(AboutEntryPath);
}
static T LoadAssetAtPath<T>(string InPath) where T : UnityEngine.Object
{
return (T) AssetDatabase.LoadAssetAtPath(InPath, typeof(T));
}
#endregion
#region GUI
Color LinkColor = new Color(0f, .682f, .937f, 1f);
GUIStyle boldTextStyle,
headerTextStyle,
linkTextStyle;
GUIStyle advertisementStyle;
Vector2 scroll = Vector2.zero, adScroll = Vector2.zero;
// int mm = 32;
void OnGUI()
{
headerTextStyle = headerTextStyle ?? new GUIStyle( EditorStyles.boldLabel );//GUI.skin.label);
headerTextStyle.fontSize = 16;
linkTextStyle = linkTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
linkTextStyle.normal.textColor = LinkColor;
linkTextStyle.alignment = TextAnchor.MiddleLeft;
boldTextStyle = boldTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
boldTextStyle.fontStyle = FontStyle.Bold;
boldTextStyle.alignment = TextAnchor.MiddleLeft;
// #if UNITY_4
// richTextLabel.richText = true;
// #endif
advertisementStyle = advertisementStyle ?? new GUIStyle(GUI.skin.button);
advertisementStyle.normal.background = null;
if(banner != null)
GUILayout.Label(banner);
// mm = EditorGUI.IntField(new Rect(Screen.width - 200, 100, 200, 18), "W: ", mm);
// grr stupid rich text faiiilluuure
{
GUILayout.Label("Thank you for purchasing " + ProductName + ". Your support allows us to keep developing this and future tools for everyone.", EditorStyles.wordWrappedLabel);
GUILayout.Space(2);
GUILayout.Label("Read these quick \"ProTips\" before starting:", headerTextStyle);
GUILayout.BeginHorizontal();
GUILayout.Label("1) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Register", boldTextStyle, GUILayout.MinWidth(58), GUILayout.MaxWidth(58));
GUILayout.Label("for instant email updates, send your invoice # to", GUILayout.MinWidth(284), GUILayout.MaxWidth(284));
if( GUILayout.Button("[email protected]", linkTextStyle, GUILayout.MinWidth(142), GUILayout.MaxWidth(142)) )
Application.OpenURL("mailto:[email protected]?subject=Sign me up for the Beta!");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("2) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Report bugs", boldTextStyle, GUILayout.MinWidth(82), GUILayout.MaxWidth(82));
GUILayout.Label("to the ProCore Forum at", GUILayout.MinWidth(144), GUILayout.MaxWidth(144));
if( GUILayout.Button("www.procore3d.com/forum", linkTextStyle, GUILayout.MinWidth(162), GUILayout.MaxWidth(162)) )
Application.OpenURL("http://www.procore3d.com/forum");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("3) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Customize!", boldTextStyle, GUILayout.MinWidth(74), GUILayout.MaxWidth(74));
GUILayout.Label("Click on \"Edit > Preferences\" then \"" + ProductName + "\"", GUILayout.MinWidth(276), GUILayout.MaxWidth(276));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("4) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Documentation", boldTextStyle, GUILayout.MinWidth(102), GUILayout.MaxWidth(102));
GUILayout.Label("Tutorials, & more info:", GUILayout.MinWidth(132), GUILayout.MaxWidth(132));
if( GUILayout.Button("www.procore3d.com/" + ProductName.ToLower(), linkTextStyle, GUILayout.MinWidth(190), GUILayout.MaxWidth(190)) )
Application.OpenURL("http://www.procore3d.com/" + ProductName.ToLower());
GUILayout.EndHorizontal();
GUILayout.Space(4);
GUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
GUILayout.Label("Links:", boldTextStyle);
linkTextStyle.fontStyle = FontStyle.Italic;
linkTextStyle.alignment = TextAnchor.MiddleCenter;
if( GUILayout.Button("procore3d.com", linkTextStyle))
Application.OpenURL("http://www.procore3d.com");
if( GUILayout.Button("facebook", linkTextStyle))
Application.OpenURL("http://www.facebook.com/probuilder3d");
if( GUILayout.Button("twitter", linkTextStyle))
Application.OpenURL("http://www.twitter.com/probuilder3d");
linkTextStyle.fontStyle = FontStyle.Normal;
GUILayout.EndHorizontal();
GUILayout.Space(4);
}
HorizontalLine();
// always bold the first line (cause it's the version info stuff)
scroll = EditorGUILayout.BeginScrollView(scroll);
GUILayout.Label(ProductName + " | version: " + ProductVersion, EditorStyles.boldLabel);
GUILayout.Label("\n" + changelog);
EditorGUILayout.EndScrollView();
HorizontalLine();
GUILayout.Label("More ProCore Products", EditorStyles.boldLabel);
int pad = advertisements.Length * AD_HEIGHT > Screen.width ? 22 : 6;
adScroll = EditorGUILayout.BeginScrollView(adScroll, false, false, GUILayout.MinHeight(AD_HEIGHT + pad), GUILayout.MaxHeight(AD_HEIGHT + pad));
GUILayout.BeginHorizontal();
foreach(AdvertisementThumb ad in advertisements)
{
if(ad.url.ToLower().Contains(ProductName.ToLower()))
continue;
if(GUILayout.Button(ad.guiContent, advertisementStyle,
GUILayout.MinWidth(AD_HEIGHT), GUILayout.MaxWidth(AD_HEIGHT),
GUILayout.MinHeight(AD_HEIGHT), GUILayout.MaxHeight(AD_HEIGHT)))
{
Application.OpenURL(ad.url);
}
}
GUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
/* shill other products */
}
/**
* Draw a horizontal line across the screen and update the guilayout.
*/
void HorizontalLine()
{
Rect r = GUILayoutUtility.GetLastRect();
Color og = GUI.backgroundColor;
GUI.backgroundColor = Color.black;
GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), "");
GUI.backgroundColor = og;
GUILayout.Space(6);
}
#endregion
#region Data Parsing
/* rich text ain't wuurkin' in unity 3.5 */
const string RemoveBraketsRegex = "(\\<.*?\\>)";
/**
* Open VersionInfo and Changelog and pull out text to populate vars for OnGUI to display.
*/
void PopulateDataFields(string entryPath)
{
/* Get data from VersionInfo.txt */
TextAsset versionInfo = LoadAssetAtPath<TextAsset>( entryPath );
ProductName = "";
// ProductIdentifer = "";
ProductVersion = "";
ChangelogPath = "";
if(versionInfo != null)
{
string[] txt = versionInfo.text.Split('\n');
foreach(string cheese in txt)
{
if(cheese.StartsWith("name:"))
ProductName = cheese.Replace("name: ", "").Trim();
else
if(cheese.StartsWith("version:"))
ProductVersion = cheese.Replace("version: ", "").Trim();
else
if(cheese.StartsWith("changelog:"))
ChangelogPath = cheese.Replace("changelog: ", "").Trim();
}
}
// notes = notes.Trim();
/* Get first entry in changelog.txt */
TextAsset changelogText = LoadAssetAtPath<TextAsset>( ChangelogPath );
if(changelogText)
{
string[] split = Regex.Split(changelogText.text, "(?mi)^#\\s", RegexOptions.Multiline);
StringBuilder sb = new StringBuilder();
string[] newLineSplit = split[1].Trim().Split('\n');
for(int i = 2; i < newLineSplit.Length; i++)
sb.AppendLine(newLineSplit[i]);
changelog = sb.ToString();
}
}
private static bool GetField(string path, string field, out string value)
{
TextAsset entry = LoadAssetAtPath<TextAsset>(path);
value = "";
if(!entry) return false;
foreach(string str in entry.text.Split('\n'))
{
if(str.Contains(field))
{
value = str.Replace(field, "").Trim();
return true;
}
}
return false;
}
#endregion
}
| |
using System;
namespace ClosedXML.Excel
{
public enum XLShiftDeletedCells { ShiftCellsUp, ShiftCellsLeft }
public enum XLTransposeOptions { MoveCells, ReplaceCells }
public enum XLSearchContents { Values, Formulas, ValuesAndFormulas }
public interface IXLRange : IXLRangeBase
{
/// <summary>
/// Gets the cell at the specified row and column.
/// <para>The cell address is relative to the parent range.</para>
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, int column);
/// <summary>Gets the cell at the specified address.</summary>
/// <para>The cell address is relative to the parent range.</para>
/// <param name="cellAddressInRange">The cell address in the parent range.</param>
IXLCell Cell(string cellAddressInRange);
/// <summary>
/// Gets the cell at the specified row and column.
/// <para>The cell address is relative to the parent range.</para>
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, string column);
/// <summary>Gets the cell at the specified address.</summary>
/// <para>The cell address is relative to the parent range.</para>
/// <param name="cellAddressInRange">The cell address in the parent range.</param>
IXLCell Cell(IXLAddress cellAddressInRange);
/// <summary>
/// Gets the specified column of the range.
/// </summary>
/// <param name="columnNumber">The column number.</param>
/// <returns></returns>
IXLRangeColumn Column(int columnNumber);
/// <summary>
/// Gets the specified column of the range.
/// </summary>
/// <param name="columnLetter">Column letter.</param>
IXLRangeColumn Column(string columnLetter);
/// <summary>
/// Gets the first column of the range.
/// </summary>
IXLRangeColumn FirstColumn(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the first column of the range that contains a cell with a value.
/// </summary>
IXLRangeColumn FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumn FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the last column of the range.
/// </summary>
IXLRangeColumn LastColumn(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the last column of the range that contains a cell with a value.
/// </summary>
IXLRangeColumn LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumn LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets a collection of all columns in this range.
/// </summary>
IXLRangeColumns Columns(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets a collection of the specified columns in this range.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLRangeColumns Columns(int firstColumn, int lastColumn);
/// <summary>
/// Gets a collection of the specified columns in this range.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLRangeColumns Columns(string firstColumn, string lastColumn);
/// <summary>
/// Gets a collection of the specified columns in this range, separated by commas.
/// <para>e.g. Columns("G:H"), Columns("10:11,13:14"), Columns("P:Q,S:T"), Columns("V")</para>
/// </summary>
/// <param name="columns">The columns to return.</param>
IXLRangeColumns Columns(string columns);
/// <summary>
/// Returns the first row that matches the given predicate
/// </summary>
IXLRangeColumn FindColumn(Func<IXLRangeColumn, Boolean> predicate);
/// <summary>
/// Returns the first row that matches the given predicate
/// </summary>
IXLRangeRow FindRow(Func<IXLRangeRow, Boolean> predicate);
/// <summary>
/// Gets the first row of the range.
/// </summary>
IXLRangeRow FirstRow(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the first row of the range that contains a cell with a value.
/// </summary>
IXLRangeRow FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRow FirstRowUsed(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the last row of the range.
/// </summary>
IXLRangeRow LastRow(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the last row of the range that contains a cell with a value.
/// </summary>
IXLRangeRow LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRow LastRowUsed(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the specified row of the range.
/// </summary>
/// <param name="row">The range row.</param>
IXLRangeRow Row(int row);
IXLRangeRows Rows(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets a collection of the specified rows in this range.
/// </summary>
/// <param name="firstRow">The first row to return.</param>
/// <param name="lastRow">The last row to return.</param>
/// <returns></returns>
IXLRangeRows Rows(int firstRow, int lastRow);
/// <summary>
/// Gets a collection of the specified rows in this range, separated by commas.
/// <para>e.g. Rows("4:5"), Rows("7:8,10:11"), Rows("13")</para>
/// </summary>
/// <param name="rows">The rows to return.</param>
IXLRangeRows Rows(string rows);
/// <summary>
/// Returns the specified range.
/// </summary>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(IXLRangeAddress rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <para>e.g. Range("A1"), Range("A1:C2")</para>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(string rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCell">The first cell in the range.</param>
/// <param name="lastCell"> The last cell in the range.</param>
IXLRange Range(IXLCell firstCell, IXLCell lastCell);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the range.</param>
/// <param name="lastCellAddress"> The last cell address in the range.</param>
IXLRange Range(string firstCellAddress, string lastCellAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the range.</param>
/// <param name="lastCellAddress"> The last cell address in the range.</param>
IXLRange Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress);
/// <summary>Returns a collection of ranges, separated by commas.</summary>
/// <para>e.g. Ranges("A1"), Ranges("A1:C2"), Ranges("A1:B2,D1:D4")</para>
/// <param name="ranges">The ranges to return.</param>
IXLRanges Ranges(string ranges);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellRow"> The first cell's row of the range to return.</param>
/// <param name="firstCellColumn">The first cell's column of the range to return.</param>
/// <param name="lastCellRow"> The last cell's row of the range to return.</param>
/// <param name="lastCellColumn"> The last cell's column of the range to return.</param>
/// <returns>.</returns>
IXLRange Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn);
/// <summary>Gets the number of rows in this range.</summary>
int RowCount();
/// <summary>Gets the number of columns in this range.</summary>
int ColumnCount();
/// <summary>
/// Inserts X number of columns to the right of this range.
/// <para>All cells to the right of this range will be shifted X number of columns.</para>
/// </summary>
/// <param name="numberOfColumns">Number of columns to insert.</param>
IXLRangeColumns InsertColumnsAfter(int numberOfColumns);
IXLRangeColumns InsertColumnsAfter(int numberOfColumns, Boolean expandRange);
/// <summary>
/// Inserts X number of columns to the left of this range.
/// <para>This range and all cells to the right of this range will be shifted X number of columns.</para>
/// </summary>
/// <param name="numberOfColumns">Number of columns to insert.</param>
IXLRangeColumns InsertColumnsBefore(int numberOfColumns);
IXLRangeColumns InsertColumnsBefore(int numberOfColumns, Boolean expandRange);
/// <summary>
/// Inserts X number of rows on top of this range.
/// <para>This range and all cells below this range will be shifted X number of rows.</para>
/// </summary>
/// <param name="numberOfRows">Number of rows to insert.</param>
IXLRangeRows InsertRowsAbove(int numberOfRows);
IXLRangeRows InsertRowsAbove(int numberOfRows, Boolean expandRange);
/// <summary>
/// Inserts X number of rows below this range.
/// <para>All cells below this range will be shifted X number of rows.</para>
/// </summary>
/// <param name="numberOfRows">Number of rows to insert.</param>
IXLRangeRows InsertRowsBelow(int numberOfRows);
IXLRangeRows InsertRowsBelow(int numberOfRows, Boolean expandRange);
/// <summary>
/// Deletes this range and shifts the surrounding cells accordingly.
/// </summary>
/// <param name="shiftDeleteCells">How to shift the surrounding cells.</param>
void Delete(XLShiftDeletedCells shiftDeleteCells);
/// <summary>
/// Transposes the contents and styles of all cells in this range.
/// </summary>
/// <param name="transposeOption">How to handle the surrounding cells when transposing the range.</param>
void Transpose(XLTransposeOptions transposeOption);
IXLTable AsTable();
IXLTable AsTable(String name);
IXLTable CreateTable();
IXLTable CreateTable(String name);
IXLRange RangeUsed();
IXLRange CopyTo(IXLCell target);
IXLRange CopyTo(IXLRangeBase target);
IXLSortElements SortRows { get; }
IXLSortElements SortColumns { get; }
IXLRange Sort();
IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange SetDataType(XLCellValues dataType);
/// <summary>
/// Clears the contents of this range.
/// </summary>
/// <param name="clearOptions">Specify what you want to clear.</param>
new IXLRange Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats);
IXLRangeRows RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRows RowsUsed(Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeColumns ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumns ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate = null);
}
}
| |
// 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.Diagnostics;
namespace System.Text
{
internal static partial class Utf16Utility
{
/// <summary>
/// Returns true iff the UInt32 represents two ASCII UTF-16 characters in machine endianness.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool AllCharsInUInt32AreAscii(uint value)
{
return (value & ~0x007F_007Fu) == 0;
}
/// <summary>
/// Returns true iff the UInt64 represents four ASCII UTF-16 characters in machine endianness.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool AllCharsInUInt64AreAscii(ulong value)
{
return (value & ~0x007F_007F_007F_007Ful) == 0;
}
/// <summary>
/// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant
/// lowercase representation of those characters. Requires the input value to contain
/// two ASCII UTF-16 characters in machine endianness.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static uint ConvertAllAsciiCharsInUInt32ToLowercase(uint value)
{
// ASSUMPTION: Caller has validated that input value is ASCII.
Debug.Assert(AllCharsInUInt32AreAscii(value));
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A'
uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u;
// the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z'
uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu;
// the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z'
uint combinedIndicator = (lowerIndicator ^ upperIndicator);
// the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'A' and <= 'Z'
uint mask = (combinedIndicator & 0x0080_0080u) >> 2;
return value ^ mask; // bit flip uppercase letters [A-Z] => [a-z]
}
/// <summary>
/// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant
/// uppercase representation of those characters. Requires the input value to contain
/// two ASCII UTF-16 characters in machine endianness.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static uint ConvertAllAsciiCharsInUInt32ToUppercase(uint value)
{
// ASSUMPTION: Caller has validated that input value is ASCII.
Debug.Assert(AllCharsInUInt32AreAscii(value));
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a'
uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u;
// the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z'
uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu;
// the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z'
uint combinedIndicator = (lowerIndicator ^ upperIndicator);
// the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'a' and <= 'z'
uint mask = (combinedIndicator & 0x0080_0080u) >> 2;
return value ^ mask; // bit flip lowercase letters [a-z] => [A-Z]
}
/// <summary>
/// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff
/// the input contains one or more lowercase ASCII characters.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool UInt32ContainsAnyLowercaseAsciiChar(uint value)
{
// ASSUMPTION: Caller has validated that input value is ASCII.
Debug.Assert(AllCharsInUInt32AreAscii(value));
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a'
uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u;
// the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z'
uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu;
// the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z'
uint combinedIndicator = (lowerIndicator ^ upperIndicator);
return (combinedIndicator & 0x0080_0080u) != 0;
}
/// <summary>
/// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff
/// the input contains one or more uppercase ASCII characters.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool UInt32ContainsAnyUppercaseAsciiChar(uint value)
{
// ASSUMPTION: Caller has validated that input value is ASCII.
Debug.Assert(AllCharsInUInt32AreAscii(value));
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A'
uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u;
// the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z'
uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu;
// the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z'
uint combinedIndicator = (lowerIndicator ^ upperIndicator);
return (combinedIndicator & 0x0080_0080u) != 0;
}
/// <summary>
/// Given two UInt32s that represent two ASCII UTF-16 characters each, returns true iff
/// the two inputs are equal using an ordinal case-insensitive comparison.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool UInt32OrdinalIgnoreCaseAscii(uint valueA, uint valueB)
{
// ASSUMPTION: Caller has validated that input values are ASCII.
Debug.Assert(AllCharsInUInt32AreAscii(valueA));
Debug.Assert(AllCharsInUInt32AreAscii(valueB));
// a mask of all bits which are different between A and B
uint differentBits = valueA ^ valueB;
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value < 'A'
uint lowerIndicator = valueA + 0x0100_0100u - 0x0041_0041u;
// the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value > 'z'
uint upperIndicator = (valueA | 0x0020_0020u) + 0x0080_0080u - 0x007B_007Bu;
// the 0x80 bit of each word of 'combinedIndicator' will be set iff the word is *not* [A-Za-z]
uint combinedIndicator = lowerIndicator | upperIndicator;
// Shift all the 0x80 bits of 'combinedIndicator' into the 0x20 positions, then set all bits
// aside from 0x20. This creates a mask where all bits are set *except* for the 0x20 bits
// which correspond to alpha chars (either lower or upper). For these alpha chars only, the
// 0x20 bit is allowed to differ between the two input values. Every other char must be an
// exact bitwise match between the two input values. In other words, (valueA & mask) will
// convert valueA to uppercase, so (valueA & mask) == (valueB & mask) answers "is the uppercase
// form of valueA equal to the uppercase form of valueB?" (Technically if valueA has an alpha
// char in the same position as a non-alpha char in valueB, or vice versa, this operation will
// result in nonsense, but it'll still compute as inequal regardless, which is what we want ultimately.)
// The line below is a more efficient way of doing the same check taking advantage of the XOR
// computation we performed at the beginning of the method.
return (((combinedIndicator >> 2) | ~0x0020_0020u) & differentBits) == 0;
}
/// <summary>
/// Given two UInt64s that represent four ASCII UTF-16 characters each, returns true iff
/// the two inputs are equal using an ordinal case-insensitive comparison.
/// </summary>
/// <remarks>
/// This is a branchless implementation.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool UInt64OrdinalIgnoreCaseAscii(ulong valueA, ulong valueB)
{
// ASSUMPTION: Caller has validated that input values are ASCII.
Debug.Assert(AllCharsInUInt64AreAscii(valueA));
Debug.Assert(AllCharsInUInt64AreAscii(valueB));
// the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A'
ulong lowerIndicator = valueA + 0x0080_0080_0080_0080ul - 0x0041_0041_0041_0041ul;
// the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value <= 'z'
ulong upperIndicator = (valueA | 0x0020_0020_0020_0020ul) + 0x0100_0100_0100_0100ul - 0x007B_007B_007B_007Bul;
// the 0x20 bit of each word of 'combinedIndicator' will be set iff the word is [A-Za-z]
ulong combinedIndicator = (0x0080_0080_0080_0080ul & lowerIndicator & upperIndicator) >> 2;
// Convert both values to lowercase (using the combined indicator from the first value)
// and compare for equality. It's possible that the first value will contain an alpha character
// where the second value doesn't (or vice versa), and applying the combined indicator will
// create nonsensical data, but the comparison would have failed anyway in this case so it's
// a safe operation to perform.
//
// This 64-bit method is similar to the 32-bit method, but it performs the equivalent of convert-to-
// lowercase-then-compare rather than convert-to-uppercase-and-compare. This particular operation
// happens to be faster on x64.
return (valueA | combinedIndicator) == (valueB | combinedIndicator);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.