context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
namespace Common
{
public class SourceCodePrinting
{
// TODO wherever you split on primitive types,
// have you considered all these:
// sbyte, byte, short, ushort, int, uint, long, ulong, char, bool, float, double, decimal
public static String toSourceCodeString(String s)
{
if (s == null) throw new ArgumentNullException("s");
StringBuilder w = new StringBuilder();
w.Append("(new String(new char[] {");
for (int i = 0; i < s.Length; i++)
{
if (i > 0) w.Append(",");
int x = s[i];
w.Append(ToUniCode(x));
}
w.Append("}))");
return w.ToString();
}
public static string ToSourceCodeString(char c)
{
return ToUniCode(Convert.ToInt32(c));
}
private static string ToUniCode(int i)
{
return "'\\u" + String.Format("{0:x2}", i).PadLeft(4, '0') + "'";
}
public static string ToCodeString2(byte e)
{
if (e == byte.MaxValue)
return "byte.MaxValue";
if (e == byte.MinValue)
return "byte.MinValue";
return WrapNumberIfNegative(e.ToString());
}
public static string ToCodeString2(short e)
{
if (e == short.MaxValue)
return "short.MaxValue";
if (e == short.MinValue)
return "short.MinValue";
return WrapNumberIfNegative(e.ToString());
}
public static string ToCodeString2(int e)
{
if (e == int.MaxValue)
return "int.MaxValue";
if (e == int.MinValue)
return "int.MinValue";
return WrapNumberIfNegative(e.ToString());
}
public static string ToCodeString2(long e)
{
if (e == long.MaxValue)
return "long.MaxValue";
if (e == long.MinValue)
return "long.MinValue";
return WrapNumberIfNegative(e.ToString());
}
public static string ToCodeString2(float e)
{
if (e == float.MaxValue)
return "float.MaxValue";
if (e == float.MinValue)
return "float.MinValue";
if (e == float.Epsilon)
return "float.Epsilon";
if (float.IsNaN(e))
return "float.NaN";
if (float.IsNegativeInfinity(e))
return "float.NegativeInfinity";
if (float.IsPositiveInfinity(e))
return "float.PositiveInfinity";
return WrapNumberIfNegative(e.ToString());
}
public static string ToCodeString2(double e)
{
if (e == double.MaxValue)
return "double.MaxValue";
if (e == double.MinValue)
return "double.MinValue";
if (e == double.Epsilon)
return "double.Epsilon";
if (double.IsNaN(e))
return "double.NaN";
if (double.IsNegativeInfinity(e))
return "double.NegativeInfinity";
if (double.IsPositiveInfinity(e))
return "double.PositiveInfinity";
return WrapNumberIfNegative(e.ToString());
}
private static string WrapNumberIfNegative(string p)
{
if (p[0] == '-')
return "(" + p + ")";
return p;
}
/// <summary>
/// A string representing the given enumeration, as C# code.
/// </summary>
public static string ToCodeString(Enum e)
{
// Get all the values that e represents.
Collection<string> values = new Collection<string>();
if (e.ToString().Contains(","))
{
foreach (string value in e.ToString().Split(",".ToCharArray()))
{
values.Add(value.Trim());
}
}
else
{
values.Add(e.ToString());
}
// Return the logical OR of the values.
StringBuilder b = new StringBuilder();
for (int i = 0; i < values.Count; i++)
{
if (i > 0)
b.Append(" | ");
b.Append(e.GetType() + "." + values[i]);
}
return b.ToString();
}
private class MyGenericType
{
private MyGenericType declaringType;
private string name;
private List<MyGenericType> genericTypeArguments;
private int numGenericTypeArgsAccum;
public static MyGenericType Create(Type t)
{
if (t == null) throw new ArgumentNullException();
if (t.ContainsGenericParameters) throw new ArgumentException("Expected closed constructed type: "
+ t);
return new MyGenericType(t, MapTypes(t));
}
private MyGenericType(Type t, Dictionary<int, Type> map)
{
if (t == null) throw new ArgumentNullException();
// Assign declaring type.
if (t.DeclaringType == null)
{
this.declaringType = Dummy();
// Assign name.
this.name = t.Namespace + "." + t.Name.Split('`')[0];
}
else
{
this.declaringType = new MyGenericType(t.DeclaringType, map);
// Assign name.
this.name = t.Name.Split('`')[0];
}
Type[] gTypes = t.GetGenericArguments();
if (gTypes.Length == 0)
{
// Assign generic type arguments.
this.genericTypeArguments = new List<MyGenericType>();
// Assign numGenericTypeArgsAccum.
this.numGenericTypeArgsAccum = this.declaringType.numGenericTypeArgsAccum;
}
else
{
Util.Assert(gTypes.Length > this.declaringType.numGenericTypeArgsAccum);
// Assign generic type arguments.
this.genericTypeArguments = new List<MyGenericType>();
int numGenArgsThis = 0;
for (int i = 0; i < gTypes.Length; ++i)
{
if (i < this.declaringType.numGenericTypeArgsAccum)
{
Util.Assert(map.ContainsKey(i));
continue;
}
numGenArgsThis++;
if (gTypes[i].IsGenericParameter)
{
Util.Assert(map.ContainsKey(i));
this.genericTypeArguments.Add(MyGenericType.Create(map[i]));
}
else
{
this.genericTypeArguments.Add(MyGenericType.Create(gTypes[i]));
}
}
// Assign numGenericTypeArgsAccum.
this.numGenericTypeArgsAccum = this.declaringType.numGenericTypeArgsAccum
+ numGenArgsThis;
}
}
//private void PrintArray(Type[] type)
//{
// Console.Write("!!! ");
// foreach (Type t in type)
// Console.Write(" " + (t == null ? "null" : t.ToString()));
// Console.WriteLine();
//}
//private void PrintMap(Dictionary<int, Type> map)
//{
// Console.WriteLine("@@@MAP");
// foreach (int t in map.Keys)
// {
// Console.WriteLine(t.ToString() + " @@@ " + map[t]);
// }
//}
// Called only from private MyGenericType constructor.
private static Dictionary<int, Type> MapTypes(Type t)
{
Dictionary<int, Type> map = new Dictionary<int, Type>();
if (t.DeclaringType == null)
return map;
Type[] tGenericArgs = t.GetGenericArguments();
Type[] tParentGenericArguments = t.DeclaringType.GetGenericArguments();
for (int i = 0; i < tParentGenericArguments.Length; i++)
{
map[i] = tGenericArgs[i];
}
return map;
}
private MyGenericType()
{
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
if (!this.declaringType.IsDummy)
{
b.Append(this.declaringType.ToString());
b.Append(".");
}
b.Append(this.name);
if (this.genericTypeArguments.Count > 0)
{
b.Append("<");
for (int i = 0; i < this.genericTypeArguments.Count; i++)
{
if (i > 0) b.Append(", ");
MyGenericType t = this.genericTypeArguments[i];
b.Append(t.ToString());
}
b.Append(">");
}
return b.ToString();
}
public bool IsDummy { get { return this.name == ""; } }
private static MyGenericType Dummy()
{
MyGenericType retval = new MyGenericType();
retval.name = "";
retval.declaringType = null;
retval.genericTypeArguments = new List<MyGenericType>();
retval.numGenericTypeArgsAccum = 0;
return retval;
}
}
public static string ToCodeString(Type t)
{
return MyGenericType.Create(t).ToString();
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Provisioning.Cloud.WorkflowWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComUtils.Framework.TableFrame.DS
{
public class sys_TableDS
{
public sys_TableDS()
{
}
private const string THIS = "PCSComUtils.Framework.TableFrame.DS.DS.sys_TableDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to sys_Table
/// </Description>
/// <Inputs>
/// sys_TableVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 27, 2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
sys_TableVO objObject = (sys_TableVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO " + sys_TableTable.TABLE_NAME + " ("
+ sys_TableTable.CODE_FLD + ","
+ sys_TableTable.TABLENAME_FLD + ","
+ sys_TableTable.TABLEORVIEW_FLD + ","
+ sys_TableTable.HEIGHT_FLD + ")"
+ "VALUES(?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.CODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLENAME_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.TABLENAME_FLD].Value = objObject.TableName;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLEORVIEW_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.TABLEORVIEW_FLD].Value = objObject.TableOrView;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.HEIGHT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_TableTable.HEIGHT_FLD].Value = objObject.Height;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE
|| ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to add a new Row into the sys_Table
/// and then a new row with newest TableId into the sys_TableAndGroup
/// </Description>
/// <Inputs>
/// sys_TableVO
/// GroupID
/// </Inputs>
/// <Outputs>
/// a new row is inserted into the sys_Table
/// and a new row is inserted into the sys_TableAndGroup
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 27, 2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void AddTable(object pobjObjectVO, int pintGroupID)
{
const string METHOD_NAME = THIS + ".AddTable()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
//Get the highest table order
int intTableOrder = MaxTableOrder(pintGroupID) + 1;
sys_TableVO objObject = (sys_TableVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO " + sys_TableTable.TABLE_NAME + " ("
+ sys_TableTable.CODE_FLD + ","
+ sys_TableTable.TABLENAME_FLD + ","
+ sys_TableTable.TABLEORVIEW_FLD + ","
+ sys_TableTable.HEIGHT_FLD + ")"
+ "VALUES(?,?,?,?)";
//; Insert into THIEN_TEST values (@@IDENTITY,'aa','aa1')
strSql += " ; INSERT INTO " + sys_TableAndGroupTable.TABLE_NAME + " ("
+ sys_TableAndGroupTable.TABLEGROUPID_FLD + ","
+ sys_TableAndGroupTable.TABLEID_FLD + ","
+ sys_TableAndGroupTable.TABLEORDER_FLD + ")"
+ "VALUES(" + pintGroupID + " ,@@IDENTITY," + intTableOrder + ")";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.CODE_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLENAME_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.TABLENAME_FLD].Value = objObject.TableName;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLEORVIEW_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.TABLEORVIEW_FLD].Value = objObject.TableOrView;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.HEIGHT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_TableTable.HEIGHT_FLD].Value = objObject.Height;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE
|| ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to add a new Row into the sys_Table
/// and then a new row with newest TableId into the sys_TableAndGroup
/// </Description>
/// <Inputs>
/// sys_TableVO
/// GroupID
/// </Inputs>
/// <Outputs>
/// a new row is inserted into the sys_Table
/// and a new row is inserted into the sys_TableAndGroup
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 27, 2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int AddTableAndReturnMaxID(object pobjObjectVO, int pintGroupID)
{
const string METHOD_NAME = THIS + ".AddTableAndReturnMaxID()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
//Get the highest table order
int intTableOrder = MaxTableOrder(pintGroupID) + 1;
sys_TableVO objObject = (sys_TableVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO " + sys_TableTable.TABLE_NAME + " ("
+ sys_TableTable.CODE_FLD + ","
+ sys_TableTable.TABLENAME_FLD + ","
+ sys_TableTable.TABLEORVIEW_FLD + ","
+ sys_TableTable.ISVIEWONLY_FLD + ","
+ sys_TableTable.HEIGHT_FLD + ")"
+ "VALUES(?,?,?,?,?)";
//This query will be used to get the latest identity value
strSql += "; SELECT @@IDENTITY as MaxID";
//; Insert into sys_TableAndGroup
strSql += " ; INSERT INTO " + sys_TableAndGroupTable.TABLE_NAME + " ("
+ sys_TableAndGroupTable.TABLEGROUPID_FLD + ","
+ sys_TableAndGroupTable.TABLEID_FLD + ","
+ sys_TableAndGroupTable.TABLEORDER_FLD + ")"
+ "VALUES(" + pintGroupID + " ,@@IDENTITY," + intTableOrder + ")";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.CODE_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLENAME_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.TABLENAME_FLD].Value = objObject.TableName;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLEORVIEW_FLD, OleDbType.Char));
ocmdPCS.Parameters[sys_TableTable.TABLEORVIEW_FLD].Value = objObject.TableOrView;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.ISVIEWONLY_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[sys_TableTable.ISVIEWONLY_FLD].Value = objObject.IsViewOnly;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.HEIGHT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_TableTable.HEIGHT_FLD].Value = objObject.Height;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
//ocmdPCS.ExecuteNonQuery();
return int.Parse(ocmdPCS.ExecuteScalar().ToString());
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE
|| ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from sys_Table
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// Modified by NgocHT
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = string.Empty;
strSql = "DELETE " + sys_TableTable.TABLE_NAME +
" WHERE " + "TableID" + "=" + pintID.ToString();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from sys_Table
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// sys_TableVO
/// </Outputs>
/// <Returns>
/// sys_TableVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 27, 2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ sys_TableTable.TABLEID_FLD + ","
+ sys_TableTable.CODE_FLD + ","
+ sys_TableTable.TABLENAME_FLD + ","
+ sys_TableTable.TABLEORVIEW_FLD + ","
+ sys_TableTable.HEIGHT_FLD
+ " FROM " + sys_TableTable.TABLE_NAME
+ " WHERE " + sys_TableTable.TABLEID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
sys_TableVO objObject = new sys_TableVO();
while (odrPCS.Read())
{
objObject.TableID = int.Parse(odrPCS[sys_TableTable.TABLEID_FLD].ToString());
objObject.Code = odrPCS[sys_TableTable.CODE_FLD].ToString().Trim();
objObject.TableName = odrPCS[sys_TableTable.TABLENAME_FLD].ToString().Trim();
objObject.TableOrView = odrPCS[sys_TableTable.TABLEORVIEW_FLD].ToString().Trim();
if (odrPCS[sys_TableTable.HEIGHT_FLD] != DBNull.Value)
objObject.Height = int.Parse(odrPCS[sys_TableTable.HEIGHT_FLD].ToString());
}
return objObject;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to sys_Table
/// </Description>
/// <Inputs>
/// sys_TableVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// Modified by NgocHT
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
sys_TableVO objObject = (sys_TableVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = string.Empty;
strSql = "UPDATE " + sys_TableTable.TABLE_NAME + " SET "
+ sys_TableTable.CODE_FLD + "= ?" + ","
+ sys_TableTable.TABLENAME_FLD + "= ?" + ","
+ sys_TableTable.TABLEORVIEW_FLD + "= ?" + ","
+ sys_TableTable.ISVIEWONLY_FLD + "= ?" + ","
+ sys_TableTable.HEIGHT_FLD + "= ?"
+ " WHERE " + sys_TableTable.TABLEID_FLD + "= ?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.CODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLENAME_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.TABLENAME_FLD].Value = objObject.TableName;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLEORVIEW_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[sys_TableTable.TABLEORVIEW_FLD].Value = objObject.TableOrView;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.ISVIEWONLY_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[sys_TableTable.ISVIEWONLY_FLD].Value = objObject.IsViewOnly;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.HEIGHT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_TableTable.HEIGHT_FLD].Value = objObject.Height;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableTable.TABLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_TableTable.TABLEID_FLD].Value = objObject.TableID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE
|| ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from sys_Table
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 29, 2004
/// </History>
/// <Notes>
/// Modified by NgocHT
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT t." + sys_TableTable.TABLEID_FLD
+ " ,t." + sys_TableTable.CODE_FLD
+ ",t." + sys_TableTable.TABLENAME_FLD
+ ",t." + sys_TableTable.TABLEORVIEW_FLD
+ ",t." + sys_TableTable.HEIGHT_FLD
+ ",t." + sys_TableTable.ISVIEWONLY_FLD
+ " FROM " + sys_TableTable.TABLE_NAME + " t"
+ " INNER JOIN " + sys_TableAndGroupTable.TABLE_NAME + " a "
+ " ON t.TableID = a.TableID "
+ " ORDER BY a." + sys_TableAndGroupTable.TABLEGROUPID_FLD
+ ",a." + sys_TableAndGroupTable.TABLEORDER_FLD;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, sys_TableTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, December 27, 2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
// OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ sys_TableTable.TABLEID_FLD + ","
+ sys_TableTable.CODE_FLD + ","
+ sys_TableTable.TABLENAME_FLD + ","
+ sys_TableTable.TABLEORVIEW_FLD + ","
+ sys_TableTable.HEIGHT_FLD;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
// odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, sys_TableTable.TABLE_NAME);
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all row in sys_table
/// </Description>
/// <Inputs>
/// N/A
/// </Inputs>
/// <Outputs>
/// dataset sys_TableVO
/// </Outputs>
/// <Returns>
/// dataset
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListTableOrView()
{
const string METHOD_NAME = THIS + ".ListTableOrView()";
DataSet dstPCS = new DataSet();
string strSql = "SELECT " + SchemaTableTable.TABLENAME_FLD
+ "," + SchemaTableTable.TABLETYPE_FLD
+ " FROM " + SchemaTableTable.TABLE_NAME
+ " ORDER BY " + SchemaTableTable.TABLENAME_FLD;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, SchemaTableTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get the max value of last row in sys_table
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// Max Table Order
/// </Outputs>
/// <Returns>
/// int
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MaxTableOrder(int pintGroupID)
{
const string METHOD_NAME = THIS + ".ReturnTableOrder()";
string strSql = "SELECT ISNULL(MAX(" + sys_TableAndGroupTable.TABLEORDER_FLD + "),0)"
+ " FROM " + sys_TableAndGroupTable.TABLE_NAME
+ " WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD
+ " = " + pintGroupID.ToString();
int nMax;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
nMax = int.Parse(ocmdPCS.ExecuteScalar().ToString());
return nMax;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get the min value of row in sys_table
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// MIN Table Order
/// </Outputs>
/// <Returns>
/// int
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 30-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MinTableOrder(int pintGroupID)
{
const string METHOD_NAME = THIS + ".ReturnTableOrder()";
string strSql = "SELECT ISNULL(MIN(" + sys_TableAndGroupTable.TABLEORDER_FLD + "),0)"
+ " FROM " + sys_TableAndGroupTable.TABLE_NAME
+ " WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD
+ " = " + pintGroupID.ToString();
int nMax;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
nMax = int.Parse(ocmdPCS.ExecuteScalar().ToString());
return nMax;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get the max value of TableID in sys_table
/// </Description>
/// <Inputs>
/// N/A
/// </Inputs>
/// <Outputs>
/// Max TableID
/// </Outputs>
/// <Returns>
/// int
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MaxTableID()
{
const string METHOD_NAME = THIS + ".MaxTableID()";
string strSql = "SELECT ISNULL(MAX(" + sys_TableTable.TABLEID_FLD + "),0)"
+ " FROM " + sys_TableTable.TABLE_NAME;
int nMax;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
nMax = int.Parse(ocmdPCS.ExecuteScalar().ToString());
return nMax;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get the TableID from sys_Table table
/// </Description>
/// <Inputs>
/// TableName
/// </Inputs>
/// <Outputs>
/// TableID
/// </Outputs>
/// <Returns>
/// string
/// </Returns>
/// <Authors>
/// THIENHD
/// </Authors>
/// <History>
/// 04-JAN-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int GetTableID(string pstrTableName)
{
const string METHOD_NAME = THIS + ".GetTableID()";
string strSql = "SELECT " + sys_TableTable.TABLEID_FLD
+ " FROM " + sys_TableTable.TABLE_NAME
+ " WHERE " + sys_TableTable.TABLEORVIEW_FLD + "='" + pstrTableName + "'";
int intTableID;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
if (ocmdPCS.ExecuteScalar() == null || ocmdPCS.ExecuteScalar().ToString().Trim() == String.Empty)
{
intTableID = -1;
}
else
{
intTableID = int.Parse(ocmdPCS.ExecuteScalar().ToString());
}
return intTableID;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetAllColumnNameOfTable
/// </summary>
/// <param name="pstrTableOrViewName"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Wednesday, Nov 30 2005</date>
public DataSet GetAllColumnNameOfTable(string pstrTableOrViewName)
{
const string METHOD_NAME = THIS + ".GetAllColumnNameOfTable()";
DataSet dstTables = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "select Table_Name, Column_Name, Is_Nullable, Data_Type, Ordinal_Position "
+ " from information_schema.columns where Table_Name = '"
+ pstrTableOrViewName + "'";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstTables, sys_TableTable.TABLE_NAME);
return dstTables;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from sys_Table
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 06-Jan-2005
/// </History>
/// <Notes>
///
/// </Notes>
//**************************************************************************
public DataSet GetAllTables()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstTables = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT " + sys_TableTable.TABLEID_FLD
+ " ," + sys_TableTable.CODE_FLD
+ "," + sys_TableTable.TABLENAME_FLD
+ "," + sys_TableTable.TABLEORVIEW_FLD
+ "," + sys_TableTable.HEIGHT_FLD
+ " FROM " + sys_TableTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstTables, sys_TableTable.TABLE_NAME);
return dstTables;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method use to get data from specified table
/// </Description>
/// <Inputs>
/// TableName, FromField, FilterField1, FilterField2
/// </Inputs>
/// <Outputs>
/// DataTable
/// </Outputs>
/// <Returns>
/// DataTable
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 02-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetDataFromTable(string pstrTableName, string pstrFromField, string pstrFilterField1, string pstrFilterField2)
{
const string METHOD_NAME = THIS + ".GetDataFromTable()";
DataSet dstTables = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT " + pstrFromField;
if ((pstrFilterField1 != string.Empty) && (pstrFilterField1 != null))
{
strSql += "," + pstrFilterField1;
}
if ((pstrFilterField2 != string.Empty) && (pstrFilterField2 != null))
{
strSql += "," + pstrFilterField2;
}
strSql += " FROM " + pstrTableName;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstTables, pstrTableName);
return dstTables.Tables[0];
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebSocketException.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.WebSockets
{
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
[Serializable]
public sealed class WebSocketException : Win32Exception
{
private WebSocketError m_WebSocketErrorCode;
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException()
: this(Marshal.GetLastWin32Error())
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error)
: this(error, GetErrorMessage(error))
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, string message) : base(message)
{
m_WebSocketErrorCode = error;
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, Exception innerException)
: this(error, GetErrorMessage(error), innerException)
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, string message, Exception innerException)
: base(message, innerException)
{
m_WebSocketErrorCode = error;
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(int nativeError)
: base(nativeError)
{
m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success;
this.SetErrorCodeOnError(nativeError);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(int nativeError, string message)
: base(nativeError, message)
{
m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success;
this.SetErrorCodeOnError(nativeError);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(int nativeError, Exception innerException)
: base(SR.GetString(SR.net_WebSockets_Generic), innerException)
{
m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success;
this.SetErrorCodeOnError(nativeError);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, int nativeError)
: this(error, nativeError, GetErrorMessage(error))
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, int nativeError, string message)
: base(message)
{
m_WebSocketErrorCode = error;
this.SetErrorCodeOnError(nativeError);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, int nativeError, Exception innerException)
: this(error, nativeError, GetErrorMessage(error), innerException)
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(WebSocketError error, int nativeError, string message, Exception innerException)
: base(message, innerException)
{
m_WebSocketErrorCode = error;
this.SetErrorCodeOnError(nativeError);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(string message)
: base(message)
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
public WebSocketException(string message, Exception innerException)
: base(message, innerException)
{
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")]
private WebSocketException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
public override int ErrorCode
{
get
{
return base.NativeErrorCode;
}
}
public WebSocketError WebSocketErrorCode
{
get
{
return m_WebSocketErrorCode;
}
}
private static string GetErrorMessage(WebSocketError error)
{
// provide a canned message for the error type
switch (error)
{
case WebSocketError.InvalidMessageType:
return SR.GetString(SR.net_WebSockets_InvalidMessageType_Generic,
typeof(WebSocket).Name + WebSocketBase.Methods.CloseAsync,
typeof(WebSocket).Name + WebSocketBase.Methods.CloseOutputAsync);
case WebSocketError.Faulted:
return SR.GetString(SR.net_Websockets_WebSocketBaseFaulted);
case WebSocketError.NotAWebSocket:
return SR.GetString(SR.net_WebSockets_NotAWebSocket_Generic);
case WebSocketError.UnsupportedVersion:
return SR.GetString(SR.net_WebSockets_UnsupportedWebSocketVersion_Generic);
case WebSocketError.UnsupportedProtocol:
return SR.GetString(SR.net_WebSockets_UnsupportedProtocol_Generic);
case WebSocketError.HeaderError:
return SR.GetString(SR.net_WebSockets_HeaderError_Generic);
case WebSocketError.ConnectionClosedPrematurely:
return SR.GetString(SR.net_WebSockets_ConnectionClosedPrematurely_Generic);
case WebSocketError.InvalidState:
return SR.GetString(SR.net_WebSockets_InvalidState_Generic);
default:
return SR.GetString(SR.net_WebSockets_Generic);
}
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("WebSocketErrorCode", m_WebSocketErrorCode);
base.GetObjectData(info, context);
}
// Set the error code only if there is an error (i.e. nativeError >= 0). Otherwise the code ----s up on deserialization
// as the Exception..ctor() throws on setting HResult to 0. The default for HResult is -2147467259.
private void SetErrorCodeOnError(int nativeError)
{
if (!WebSocketProtocolComponent.Succeeded(nativeError))
{
this.HResult = nativeError;
}
}
}
}
| |
//
// HttpListenerPrefixCollection.cs
// Copied from System.Net.HttpListenerPrefixCollection.cs
//
// Author:
// Gonzalo Paniagua Javier ([email protected])
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012-2013 sta.blockhead
//
// 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;
using System.Collections.Generic;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the collection used to store the URI prefixes for the <see cref="HttpListener"/>.
/// </summary>
public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable
{
#region Private Fields
private HttpListener _listener;
private List<string> _prefixes;
#endregion
#region Private Constructors
private HttpListenerPrefixCollection ()
{
_prefixes = new List<string> ();
}
#endregion
#region Internal Constructors
internal HttpListenerPrefixCollection (HttpListener listener)
: this ()
{
_listener = listener;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of prefixes contained in the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <value>
/// A <see cref="int"/> that contains the number of prefixes.
/// </value>
public int Count {
get {
return _prefixes.Count;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="HttpListenerPrefixCollection"/>
/// is read-only.
/// </summary>
/// <value>
/// Always returns <c>false</c>.
/// </value>
public bool IsReadOnly {
get {
return false;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="HttpListenerPrefixCollection"/>
/// is synchronized.
/// </summary>
/// <value>
/// Always returns <c>false</c>.
/// </value>
public bool IsSynchronized {
get {
return false;
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="uriPrefix"/> to the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <param name="uriPrefix">
/// A <see cref="string"/> that contains a URI prefix to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="uriPrefix"/> is invalid.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public void Add (string uriPrefix)
{
_listener.CheckDisposed ();
ListenerPrefix.CheckUriPrefix (uriPrefix);
if (_prefixes.Contains (uriPrefix))
return;
_prefixes.Add (uriPrefix);
if (_listener.IsListening)
EndPointManager.AddPrefix (uriPrefix, _listener);
}
/// <summary>
/// Removes all URI prefixes from the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public void Clear ()
{
_listener.CheckDisposed ();
_prefixes.Clear ();
if (_listener.IsListening)
EndPointManager.RemoveListener (_listener);
}
/// <summary>
/// Returns a value indicating whether the <see cref="HttpListenerPrefixCollection"/> contains
/// the specified <paramref name="uriPrefix"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the <see cref="HttpListenerPrefixCollection"/> contains <paramref name="uriPrefix"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="uriPrefix">
/// A <see cref="string"/> that contains a URI prefix to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public bool Contains (string uriPrefix)
{
_listener.CheckDisposed ();
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
return _prefixes.Contains (uriPrefix);
}
/// <summary>
/// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to
/// the specified <see cref="Array"/>.
/// </summary>
/// <param name="array">
/// An <see cref="Array"/> that receives the URI prefix strings
/// in the <see cref="HttpListenerPrefixCollection"/>.
/// </param>
/// <param name="offset">
/// An <see cref="int"/> that contains the zero-based index in <paramref name="array"/>
/// at which copying begins.
/// </param>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public void CopyTo (Array array, int offset)
{
_listener.CheckDisposed ();
((ICollection) _prefixes).CopyTo (array, offset);
}
/// <summary>
/// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to
/// the specified array of <see cref="string"/>.
/// </summary>
/// <param name="array">
/// An array of <see cref="string"/> that receives the URI prefix strings
/// in the <see cref="HttpListenerPrefixCollection"/>.
/// </param>
/// <param name="offset">
/// An <see cref="int"/> that contains the zero-based index in <paramref name="array"/>
/// at which copying begins.
/// </param>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public void CopyTo (string [] array, int offset)
{
_listener.CheckDisposed ();
_prefixes.CopyTo (array, offset);
}
/// <summary>
/// Gets an object that can be used to iterate through the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <returns>
/// An object that implements the IEnumerator<string> interface and provides access to
/// the URI prefix strings in the <see cref="HttpListenerPrefixCollection"/>.
/// </returns>
public IEnumerator<string> GetEnumerator ()
{
return _prefixes.GetEnumerator ();
}
/// <summary>
/// Removes the specified <paramref name="uriPrefix"/> from the list of prefixes
/// in the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="uriPrefix"/> is successfully found and removed;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="uriPrefix">
/// A <see cref="string"/> that contains a URI prefix to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/>
/// is closed.
/// </exception>
public bool Remove (string uriPrefix)
{
_listener.CheckDisposed ();
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
var result = _prefixes.Remove (uriPrefix);
if (result && _listener.IsListening)
EndPointManager.RemovePrefix (uriPrefix, _listener);
return result;
}
#endregion
#region Explicit Interface Implementation
/// <summary>
/// Gets an object that can be used to iterate through the <see cref="HttpListenerPrefixCollection"/>.
/// </summary>
/// <returns>
/// An object that implements the <see cref="IEnumerator"/> interface and provides access to
/// the URI prefix strings in the <see cref="HttpListenerPrefixCollection"/>.
/// </returns>
IEnumerator IEnumerable.GetEnumerator ()
{
return _prefixes.GetEnumerator ();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
namespace OpenSim.Region.DataSnapshot.Providers
{
public class ObjectSnapshot : IDataSnapshotProvider
{
// private DataSnapshotManager m_parent = null;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static UUID m_BlankImage = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
private static UUID m_DefaultImage = new UUID("89556747-24cb-43ed-920b-47caed15465f");
private Scene m_scene = null;
private bool m_stale = true;
public event ProviderStale OnStale;
public Scene GetParentScene
{
get { return m_scene; }
}
public String Name
{
get { return "ObjectSnapshot"; }
}
public bool Stale
{
get
{
return m_stale;
}
set
{
m_stale = value;
if (m_stale)
OnStale(this);
}
}
public void Initialize(Scene scene, DataSnapshotManager parent)
{
m_scene = scene;
// m_parent = parent;
//To check for staleness, we must catch all incoming client packets.
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnParcelPrimCountAdd += delegate(SceneObjectGroup obj) { this.Stale = true; };
}
public void OnNewClient(IClientAPI client)
{
//Detect object data changes by hooking into the IClientAPI.
//Very dirty, and breaks whenever someone changes the client API.
client.OnAddPrim += delegate(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot,
PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
byte RayEndIsIntersection) { this.Stale = true; };
client.OnLinkObjects += delegate(IClientAPI remoteClient, uint parent, List<uint> children)
{ this.Stale = true; };
client.OnDelinkObjects += delegate(List<uint> primIds, IClientAPI clientApi) { this.Stale = true; };
client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos,
IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; };
client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt,
bool silent) { this.Stale = true; };
client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID,
UUID GroupID) { this.Stale = true; };
client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart, bool BypassRaycast,
bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) { this.Stale = true; };
client.OnObjectIncludeInSearch += delegate(IClientAPI remoteClient, bool IncludeInSearch, uint localID)
{ this.Stale = true; };
client.OnObjectPermissions += delegate(IClientAPI controller, UUID agentID, UUID sessionID,
byte field, uint localId, uint mask, byte set) { this.Stale = true; };
client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd,
Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected,
bool RemoveItem, UUID fromTaskID) { this.Stale = true; };
}
public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
{
m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);
XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
XmlNode node;
EntityBase[] entities = m_scene.Entities.GetEntities();
foreach (EntityBase entity in entities)
{
// only objects, not avatars
if (entity is SceneObjectGroup)
{
SceneObjectGroup obj = (SceneObjectGroup)entity;
// m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");
// libomv will complain about PrimFlags.JointWheel
// being obsolete, so we...
#pragma warning disable 0612
if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
{
SceneObjectPart m_rootPart = obj.RootPart;
ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);
XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
node = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
node.InnerText = obj.UUID.ToString();
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
node.InnerText = m_rootPart.Name;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
node.InnerText = m_rootPart.Description;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
node.InnerText = String.Format("{0:x}", (uint)m_rootPart.Flags);
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
xmlobject.AppendChild(node);
if (land != null && land.LandData != null)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
node.InnerText = land.LandData.GlobalID.ToString();
xmlobject.AppendChild(node);
}
else
{
// Something is wrong with this object. Let's not list it.
m_log.WarnFormat("[DATASNAPSHOT]: Bad data for object {0} ({1}) in region {2}", obj.Name, obj.UUID, m_scene.RegionInfo.RegionName);
continue;
}
node = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
Vector3 loc = obj.AbsolutePosition;
node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
xmlobject.AppendChild(node);
string bestImage = GuessImage(obj);
if (bestImage != string.Empty)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
node.InnerText = bestImage;
xmlobject.AppendChild(node);
}
parent.AppendChild(xmlobject);
}
#pragma warning disable 0612
}
}
this.Stale = false;
return parent;
}
/// <summary>
/// Guesses the best image, based on a simple heuristic. It guesses only for boxes.
/// We're optimizing for boxes, because those are the most common objects
/// marked "Show in search" -- boxes with content inside.For other shapes,
/// it's really hard to tell which texture should be grabbed.
/// </summary>
/// <param name="sog"></param>
/// <returns></returns>
private string GuessImage(SceneObjectGroup sog)
{
string bestguess = string.Empty;
Dictionary<UUID, int> counts = new Dictionary<UUID, int>();
PrimitiveBaseShape shape = sog.RootPart.Shape;
if (shape != null && shape.ProfileShape == ProfileShape.Square)
{
Primitive.TextureEntry textures = shape.Textures;
if (textures != null)
{
if (textures.DefaultTexture != null &&
textures.DefaultTexture.TextureID != UUID.Zero &&
textures.DefaultTexture.TextureID != m_DefaultImage &&
textures.DefaultTexture.TextureID != m_BlankImage &&
textures.DefaultTexture.RGBA.A < 50f)
{
counts[textures.DefaultTexture.TextureID] = 8;
}
if (textures.FaceTextures != null)
{
foreach (Primitive.TextureEntryFace tentry in textures.FaceTextures)
{
if (tentry != null)
{
if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50)
{
int c = 0;
counts.TryGetValue(tentry.TextureID, out c);
counts[tentry.TextureID] = c + 1;
// decrease the default texture count
if (counts.ContainsKey(textures.DefaultTexture.TextureID))
counts[textures.DefaultTexture.TextureID] = counts[textures.DefaultTexture.TextureID] - 1;
}
}
}
}
// Let's pick the most unique texture
int min = 9999;
foreach (KeyValuePair<UUID, int> kv in counts)
{
if (kv.Value < min && kv.Value >= 1)
{
bestguess = kv.Key.ToString();
min = kv.Value;
}
}
}
}
return bestguess;
}
}
}
| |
using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Algorithms
{
public static class HkdfSha256Tests
{
private const string s_prkForEmpty =
"b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad";
// unverified
private const string s_outputForEmpty =
"eb70f01dede9afafa449eee1b1286504e1f62388b3f7dd4f956697b0e828fe18" +
"1e59c2ec0fe6e7e7ac2613b6ab65342a83379969da234240cded3777914db907" +
"5568c74fdb8fc92331d5c59e1e2dd77a8c2c63aba7cf2d3457f8ee8620462f8a" +
"d77a798b94238ff3092304585bda6c1581d3f9e758802ad482422fdb555604d5" +
"89ab88b2079a075576ed7ca6e6e17502db3467112a4d96bd360ad12e30a3772e" +
"0fa76c13ebfa95dad91397d243f35b2305ed7cc2dbd84c80b8df4aee2fa91d51" +
"4b6d86c288c51bc60d4f3873b77a9b5dd6c2fef654d7b93e5326251ad923a887" +
"efe6d45845c429ada72532af834137ad3bedd385bb7341b138d68a2e77d54711" +
"3262e2db7c1c9610c48fe0d1cdca59d4630dc2724ac0cb31d621805bc006fbe9" +
"0df89c35239ab1a43c42b2ba08116fe7c9f7030e24253cfb9c12fbb17de12f27" +
"b93791e88de4c54a368391a9e5658f1e6cb8d033bfa0ab14c2508eb0c8918ab1" +
"35ad25231d072da928ea5ea7996b64691c5f3bb17dca8a29122ac941c9279685" +
"c7ef13d4c41851fb593dcbf69e03334cc07056d3820df6c4c4f18be8f54db156" +
"f55ef0811aefe859fc8e5fcb7ffb632e255a7225744823230b93018746eabce0" +
"5255521a0d30b6edc313547af56f21f26ae942e9d69b644cdd1e85ca487ea794" +
"6fc10956be75c0c15c618bad29066f7ae85f44a2663b2085811fd44c8c5671ca" +
"04a715bf2e7a592d55541790fb21a3015c6789df8edf43584d9a6f5f28662a46" +
"ef35fe690519747067b7e099f28616b7da326fa71041af29739d161b37b14dd4" +
"7b4f2575d166153ef3895c7c57c4262625ad565074fb217ba6d81a29e48867a5" +
"0ac7be924b0a4a6c8b40ea487696fe1297bf1261790bc1b041eef7a1d03fce68" +
"9f58be028918e87213efc12f9dee289a6a7db814433f4ed95ffc05f7b1087cda" +
"b29728ce5c6371c827f69c39887e18ba0527e1c8ed48b20761a1828140b3690d" +
"48b1c93d3ba2a515cd25a436926e7e6915bf428885f886b3c2414e7c01d053a1" +
"2e07400f0257d92c6c1f3d2a26e3999869ca16b61e2a74d11a2b1705fc79c457" +
"163c265768e995b2ec5b7aa51d4c74ce2fb9957feefbe0c085db1a0e5dcf6cf0" +
"93432b0ee19bb0200b441752f5ad4a7e75017eee3539fc2ca5f595aad0f5c275" +
"0da5dadbde1ae9d613a86fb2b38e8aa970bf4dc9b089692977f73bad3d9ea6e2" +
"50034243aab04ff24963bb16ac33c0200244959800b269f03910d4a4144f240f" +
"6bdf05b6dc82d6a8108eef5e2ea979b8f5d2c5ac89583d0972b845aaf9f14154" +
"e83f4f0397057483220430ceb64ac4221893ee9ed51785bd7c09a3134897319d" +
"7507d1e27f76a20db1828623f31fb802990f8034a26140a23bda0715096ff52f" +
"a225f6e916fa7c8a8558077cc4fefd8962f097b8722611019257ef7cc63be449" +
"ff5b8af8c2a170c9a64700f917bcfd47875f24c6d3282908aaae663e9511bc9a" +
"c763314e9c909f73b13cb590eb9a7f1efef469410fc87701e3ed37c2a983b5d7" +
"a8b0b17742b2f6532eaf59717ce35cb4c93b64085bf261ebf6af4ba11eb1ee77" +
"46e81e36173e297d43f7680a5d3756a44dba546e117de1a1ace485339e1e3f3f" +
"2a4f0d18fcd44b68b3dbdf7ea79813ba7e39327e849dab4684bf5a4e64b08549" +
"f6e903965fe0b266499fd3bb38b24d50b741b1647ff824dd689610c5493e936c" +
"c1ff0c1a61829c9cb137f9615e10e1d4d81751834825940a7b3329054d52efc0" +
"e6cac971c9224cbf23f317237d5b1dec0266e9461d3a946a3a2c82ff25a0c344" +
"ca68d5567e350015fc82b5a7f6ee3b14744f0fedb6165d9b43edcddeddf9e80a" +
"34b2d1ffcb4617b921de86ebded96eabc555990371abd05074d7b132666257df" +
"ffe1a867948fca51cc84e857fadfc5e295bf1a5036065ed3b89332731fe2e636" +
"e9cf7dded8450751b3ca7786bc6afee62d91b03ba3bb6aa474df7cfdcddc4d8e" +
"5712446e9f86d5c6e094374a2a8a84b05d4dc4b8cae00bdf1311fc1726274203" +
"3dc519f3fc0a40f83501ef7baf4e14866908e8b017d692e63a00e0172d83de1c" +
"89bb677bf5ed31ae596ec0f75fa441794be7d03ede068671e5182abd5a8b5817" +
"7eac1a98e17876babad661bb2630a8a8f695ff62a9caadc5f9e80c49aa415d77" +
"7b30aaa6ce88b3cc660c829f4b15139baec114ef3295719a9febd9cace9f4c78" +
"89baa171d7737bb3eeecbbe98b5a8fb924fbc6b8bce9635eafede132c54471f4" +
"0bf1d84c392161d549a3e9540ae607667a162d1192d73ed5c5058379092050c7" +
"23ff5d52f571f47f51feb4f230a5c87dd5b5d72b5a6287625a14af52b4708fec" +
"bf30a4dbb867336672a0837688775c64b5dfbb00809cf840b4506508dd0206bd" +
"0e31eca1ea3d53ba19fa0e07aea0af131a70b36bd3463032a83764644d64809c" +
"86f2d6b0a5554618559faacacc4923217307086d6d750f6c24de97547ce4fdc0" +
"ea0ea7ea790ef774ee1156aa0a1adf2de928cc03e308ceff6ad629a21cad2f65" +
"d6db55c1a1fc7ee3f3ddf4c729650483a01f4a129b7b9f3f28ebf071c13321d7" +
"d0bbbc896eed27dd0d07369c5b37fe99ce37183169ba7d51f19790719eb8d27d" +
"23a3b9d4577bee0c1517b0872cb76c3c82ec07bcfbe4805ff50eeb5cddecd750" +
"04ba0aca3b9e7731d4dfbb5fa70cb0ef040350fa36c325fcf976dcd4dafe03f0" +
"c2cdd1e22200d5745c2c7a6958a5ced67773eaecd5dc72d7e848336d6394cf92" +
"487319f8144cd443d5773ab2c8edfe837feb9f30cc550eb4f0d44fbf57c7ad56" +
"81e0ee6ad9a249e5cdabafc420238d6b40ca2e251f58587432aeb592ceb66e9e" +
"0a75fec3af0a45151948b0a786a6f79ff7127d57ae522a83605f79fa0688a126" +
"0612c47a5300076a708ae8d8272b14ffc94c3f2d09f9074348ca06d81cb38fc9" +
"dd04a0c1f939f966ad8576e5ec97e03a902b3d87fbaf6e8052b61dfa9b799bc8" +
"ce2be861c311ac8106c0f4f8096a6d3466067370da6a9bdb01615c20f1567b28" +
"f320f6093e25c01d9483fcdc47128fc6f1b8f3dded19315298a33f4112af3a02" +
"b513da91819f747ec3b55345339d1a41fdc524b0fc80b0391be5a097a8fd3454" +
"c5f8fa78824cc97873cdb54ab64ce546805f740cd42e1df96613338629779cb3" +
"5e34148a88bc2c236358be8fda940c536798fb9b5f01d29a7b970f27bd0105aa" +
"515af7569da2c24ccf27d8d3df97f65abe2538132039d0da90cbab346f87cadc" +
"f606e49863dfe0127211f0894d5d65c4e382d6f4833bed6f9f29bcd9d1dfea11" +
"c45e7b75046f714fd03dd37906fe7e63919a3a351df1d9183f1ed1d97ea99b65" +
"f88838db761726c3259c4840f770241dea59602df98d2ce2c18e6e2919014f82" +
"c16c3d8f969aa7dc48187e3987e8aa814d3d333b691cb3e0edbca71abb819c30" +
"84b92cea0d027d660c072d1875a1c029ccd7d19a50aabea1a30ef4a5838b3376" +
"36a7f397a9431376b7792027ad45358411ec0e15edc1777da587461a983787b6" +
"7a96636257354e6876c2337b78ce73190496c0397f2120f4f350bfe75892d191" +
"a7bad55f34bb2720124bfb519891177963e431c41b53e6bb072919e540377fca" +
"ccbd1553b0b712d4dd7d830289962a3d57a91a5b13b3201ae3871df3d30b3e69" +
"4f5c2cb8e2fd58b510e9ccb74ad660fa4eab57fd752032d6ca1dfecb8660dc8c" +
"38752f58657848278d7b64257eade31d533e51115bbab34562f62a400ddec8a0" +
"24f9aab76e96c049cccf972ace463b78ba5dc7bce543d15b22d8586b76aefd9c" +
"fef12ac118dbf8d11d0eaed7cffe0148bddbcc2c126ae70c44d9873bac25bfd6" +
"761ef1a7704b08f226333ea1dbef185ea39ae4ee6ffff2d90c2b0514a8011909" +
"8146e8629b0fc2eff002da45f3ab6dca041ca7d07f9e573bed918539862cd58f" +
"02b88d51de8c816ad3cd5717b6493284a3b09e34ae64fc54b2ba568b4ef95834" +
"e9417b3b582f21aa28db211c33b9df77cf761c54d1ab2db573136369aded3a44" +
"466eaac59000c466df7d28bfba8178c07424cd651fc7b28f32a8e2de72d48d08" +
"f351ae8673389a08375978486759a764c332315b60bd07b4e9d76fdd8f7fd048" +
"61063c6bab78bba423464f57a83cf1125b42adf26d2656225eed95e25ae7532d" +
"a0f6588c2ffe658e3fe31a385f5408aedc51ed39e7ced048769e2e973f1a7e99" +
"ac7153e4581494ee105650b2cfbf9f7c9145d860f6b14994a3595a7cf71fec30" +
"c9f11a79d791406c601df6fe5f2a68ffa6ab728d4ddb1888ce4991ca44077b01" +
"7ecf68b6ff65c8a5baac512435b339c58b548d3e35ffabd25fcc2dfe5479b9f4" +
"3b3e4e6b055847e37211e0be70a886c90976d954a1f9da754a6e99fab1d1beb9" +
"f5a4e11e462c91d1e70c2c70dffc0cc8706fb45d06d8124e6cd20b3446395b0e" +
"e8e17ee3f39e97208765b2ac39becf12bea12327dac15007a91032fe412f7e51" +
"a0e22c99f95f6ce73e4d94149bb37bf424ac25d37ff9b3a75e80400918d145b4" +
"9ca1b67aab3c03803c578b585e160f6dc501ca160b58df45de9cb2667538ad84" +
"c8b3be6624cf0434f4b74ad9b7e2d9090cb90260c7028e92c21d2a4556aa8fef" +
"60cd8711152d52e79e506987e2758c701a64cbd61cd85526aecbaf40d91ebd75" +
"0698d0add54e6ae9c2dc4dd36c42e093f142588d99f3bb30688f587250d48f62" +
"aa7c0b067086d88d4a7ac807ff8371af3334b11211b9af979841787acd846dae" +
"5d6b1f9947caa86c821920db0f8373bb53aad4b6202462a1fe664f2f15bd756e" +
"39c6ee44d78cf4c3501809428d4b5bdb5e8be369bd31bae19685db283ceb2a1d" +
"dd348ca61203028b009735c3b97c7df6b55bdf745c4f84a0a2594c02842619dc" +
"d210586dda9fe6b1637584512365dba9a9f9e9c8401a541d97f951053296ba05" +
"ec5f955e380fc7da3fbe7c9e918f1fc515cba6f48b658d8045e56aa92d2f02d6" +
"c5e22880d8c95e8f2870597eb3cb48b6655c60d5fb92577d981b444c6433c22d" +
"931c014e9b7a9627a84f6399a9bb61099263f98ae927439eca748cda5e0effed" +
"8639847bb8698c7c02ae21fc6913d26251870c7fe6aea9f82507bf76bddb6b13" +
"12d349f6f64175740160b10f1e39f3f366cb48ae8b5130d7ea1e2e1b564f2d9b" +
"820453beb97346034a0425c81b69c5cc699442345952978aeeef39d734cdf110" +
"55d7461686c0acee68cc432781554a8f6c093c8a47223b59a0e239f81b1506ce" +
"1a9a0945c0316b7033949fb3f98216b00310771adebafcafd76f71707cf181a5" +
"74d86cbd7c55431e765db1dc77b61161d4e31763b0104442a38799204cf7b70a" +
"578885c7e587eef6a43d009f0635cb5393f1753e905038d63c056afb23deafbf" +
"15feab7789f8c37ac963d3e7f5fa9c8480b6dcf7905f1fda8b21e8d0302d1f01" +
"d6fafc5d910405eaa780e633af68130fae19bc46acc0be8c0c2dfc2305ff9a36" +
"241fb704297a182dfc2c1bc122c655902335f75f5cb27e457022154c0ba61327" +
"e7f296ba34173381996e0e1b257c47702a6b8d407d9f8b12ddf5ca81ecf30b5f" +
"d3050190042703e6822c95ac58457e7b523f66099e834796323961df01043ee8" +
"4972f6f748d4081201d5510735c67c82e6e43d48bc3b483b8b3d4830139477ff" +
"4e9974aa712c9fecc491b11c11bf30b1884b75ada9c2fd40ac40cec0c0397787" +
"ec330608a1340d782854c271c7723b21738ecb1f51391144f9dcbc70ad6c6587" +
"9013fa5407bb4f7d4af222d47eaf1652b0fac38629f81a929f9444ce9bc15445" +
"7adfbc37585f275f475a336799e4e4eff5931037fcdee8692de4b1a773030a3a" +
"b5ceaf77dbe5a1e1aa760d048c6fa096e76fd64accb1ef6bdce32f0d2b0844e7" +
"9441b2250a37e39c51189be672886890f7a4cec7ab5dbb1937b36294d2972d16" +
"6c7189cb20b4e3876dc0d7dc810b79064183deb5f0cf5bdd7cf1646ed2c281d2" +
"73d447339cfd2f320ef4d56a4713a6e898f190df698c16c4e3ad0dd7854e7c19" +
"51ee385cef896641a1d0ddf18afb2160c4c811ea576ac9fc73937763f66221a5" +
"630eba26254b8796b80d467e71a37c9c3113f0643356069041c4f2201ebbfc3b" +
"272c2813deefd1f7751bd1eea70b12fe9c95711c489ced326be19e699bc889ea" +
"fdee7396f7a89ce24dfb0ad225f466f19c1cd2bb3863fafbc6482fcb46762331" +
"2a1ccaee0bdc9fe8b736926b4ad33e53119af47bd2c421eff6306395dbf32105" +
"bcb18a169bb0cea8767d5198cd9e208ce9f85f2d1f1d4bd66754aab8f4647d47" +
"f84ff6f445a7df5788db52d2725d07b241ae4ffc95f949a46fe60e336aad5922" +
"2f7f597084db8ca824fa1c5f0cd560f62d498c34a5cda933f44471d9ec6495a8" +
"aaee55937e0c8d10984a28f9071437768936655be6d7f45d97c9351ecc092366" +
"a2049a737b00a2118750fe52a317c418b83a5183b79239ecb7a8525af9065a56" +
"9d0f0f4d396857a560c6e17cf89a2640c7d714f6430e03c63087afa52549431c" +
"1684d65179774ce2f9d2d9014a8e064300f4228ba7e8460661e6378c7f032f1e" +
"5cfee69b7f6874beabaaa5021f95c716cf6265e78bda34cb3001aa2f3812046d" +
"442e8ddf2ef2008c6573da085fd497a01ee40aacc640a8093e79e0135b429fc4" +
"af80b0a08362666ca2e10b9b1dc91d3692000079d1734e4a4a553aff3e36f1f0" +
"f1b9d491ad13c25448b0dfe46766f5de46dc227553bdca808d88c44ddfbe4831" +
"59d569326896e57f2a3c1e5ea6edcf5093717d1821862478d693b87f7deef7d6" +
"db3b3f77fc54d355fdb5c5cd27dffa7104cdea0710b1b075145c8447cf0199b3" +
"b69c746ec56957ee7ed630a7951e7b9a2dc284270f7f7db5b2994fc50629841b" +
"e957c8c623ec7263fd68acfe53c5bc275e402cc1341ad31fdb31ecaed65dcade" +
"7353ccf7c855ef71f92f625901617a70ab8b854b3d26b35006e9ed8c9886ed04" +
"a74a8e749654469eb77d9185e5b1871af38be067e3a70fe3dcda45df4dd5f159" +
"4e4bcfc80f24bebdac8344816ebabca60b16f5235464b7f67918bc6ff76304e1" +
"b4616a6671fb360237b54cfd894927752d87cb1d3b4e5e1a152e72b647f05992" +
"76d8ff8883d9d551f9472b457ed430a5b36bbf41a3ea36b9ccf8a79983924383" +
"efa7a5a83a4765fe4aefe0576bb74b307828df51952c91a5e2834333940084a5" +
"adc71ebe37c8d876eb21d1b337ca66ec41ec9606ccb2cf8252bd7a38302f9147" +
"dea0fe4b3a5add75d6518b6c1b1eee2bf57bb17dd64b9a01928c1311a0cc3db2" +
"bdbf2bcda88cbdeb8d45fbf2e39626baf0798b600bfab3cba2a9e97a11e30b65" +
"8943a045cbddc64ffd11187429de7bacde43b34b098c673472701f1176d23263" +
"ac8244337d5f5c16f640dfed98fdab1a5b2d57efd3fbb52093689c5d57e0c6db" +
"c18546e011d176aed23820623013db6a319768f5ac5c4e7d3b377772a8bc7a9a" +
"526f8b58aab640725fee0f4c323ad9d92aa8330b424fa7899eeb4f3835d23d74" +
"3e449023473e6ffe8710cfc169fee62adeeb120cfe77a53fa2514a4f0199315c" +
"614b5582c0160a841cce1cadd4dd9467156132e36e308d53d9edb131c2a0e10e" +
"1668fdc5141a673baa2f6cd474e46dec3a72ebd72488fa9611b7084a1e42cc96" +
"d9c12f30b28aa0e4a841895c58c186b97d70b3cfee4d50000888b7799aedf743" +
"0bf6b1b940b9a61bc4b4b8908d28a85f2d101aaa43df1d95a46e06b40749173c" +
"66a5796c31e6b5727d5d7e01bbecd96b9df13c2cebab0df7e87b0d904dd48e17" +
"a7fea0a5da5136d076936abf51ee152abb8da18d55b8a6fa8a377dba3d5cad84" +
"1597be94b48da4babb790f9d62e94308947102a1498b35e4175f72377667b074" +
"c0243b12c058b1e64887d5a5f357f60f7cdea0fe09f82dbb63e6b684b41e0ffa" +
"b5fc7e7e32b0f4e1767ea81ac0f315e166bdda030ea36cbff05ee116568d1ab0" +
"92781e53e2b6e6ac40a7d8f3312d629e48dcc8a2268f2ca9e6dc5d44f82c8f3f" +
"42bb300d84ae433820d57512940e087638294a582fdb5db4fb6b470b8863a44c" +
"8f0d0bf4fb802201438965db694776bb6e6f24b3218f4a48ec049c2a9436e572" +
"e4a3d5b491829778854b198e1167f34577cf436a77e6fc1baff380618f8c2a1a" +
"e7840370ada35428169d94b9e80fbf9dd039b36ffa26fde56cf59b5699134ec2" +
"a337adb3cf422496c8ab3e993d6f9dd1b78ab6a33185c6dcf19ec4e09b1dc116" +
"9b0bdcac4b831890c7282849311c6006e2d62bbf72345789d497a5bf0a57b1ff" +
"aa11bdf4db75fcaacdb895639d58740e559818a5c7804cc170f0bdfb5f777a62" +
"2fc397974ee9061a0262d210224037feb8ae2565dc59b439b8d8287ac70e1257" +
"67cecf20c74fe88755b96235b466b2e7f32e3fd2539657a5bafa83547a412407" +
"c4f32e1e01750f1d3498574a34cc1f9c87edde2ee8751ba04a4fabb81e740726" +
"638764221c29eb9c32c0b9366e6ca73a9c55d75bf9434035b622567187482684" +
"31750be3a784169e7e4082a020c6f40324fdbc977220f77c510615ae5f129bbc" +
"dca3b800ebe0d01e3267e899dbccced0946b62fe60083de2f86164c7c4a37c56" +
"02ef50eb14476aa3ec96f055a1253cbcd73d93766b64a55486fbeb0029e5480d" +
"535a5ca2eef2473602ed643ff02f05f00823991d830f2554fe5813265bf9ad6d" +
"bbd956ff63c2496b947da4c6e1e6dd6bef9346f1840a378c94f92ece94c7973c" +
"8a26e7963bf47dfe5cbba129807efbca9ddab3cd92684271176dea24f6b501f2" +
"491e0317c8255c2a1f7c20647f7507c85a7a7569c1822c64e79d3d3ecbab6110" +
"f95016315f9cb75fbff2a2b6b7a09c7c27a26c0b5eb5a1e6d71d9cda8061f9e8" +
"39ce0172bc76ddf1d36f5fe7c88676ec6fc9da09628706b6ad62fe98f4a70180" +
"997ac64f8565d567aee329fd8c6dda07048e26bed872b5726edd3d8c6c1dd674" +
"6d3523b4bf2f15b1fb0a0dfe3d7495eaf080c72db76508f936879d83f7d79a4a" +
"31a31e2c16f1d9cfe2ff174a695e16972a8d76b0ee9ba45e876b0896cb5cc16a" +
"d82b6cbaa83533aad9fb6085343fc841c964d7c29a8c5d993981d9d971f3f4e2" +
"c06d6635d0815a6b1134185073d26d91d63317ffe719f12b7d57fd95db09f2df" +
"1c6b8015c85506ae674c25cca201c73e5eb48621fa213d5ba546ab5bc8d0f37e" +
"c75b2179f5d28634d9ad6fe2ad8daee5d6d0318d37435b5be8d0135e20aded95" +
"aa81a612262cdf24c6fa41b3c5446fb08d6643031c56126b6dad48641c67825e" +
"4331e3a1ca88b400189d19a2d940537c07a9bad3cba6c3afdab0a7877e5e2e37" +
"5b44a4bb005395137d3e7d735865241b616e9ced1a7ce2145a1e65709ffc24f8" +
"6ab70d375a713069ab5cbe781dd3a8755135031c6c8dcf7bb9c2af8142ccadf2" +
"b387951304c79de0fbe99baa519ab844f5878f5419b6c98523ae6290858a7789" +
"fc3d39e79fac53f721355e4bb27d273f11b9972ede30b42eb7668c4715405e24" +
"594702eecf0b9db00c37abe1e3ddc6f3b9d1e579a3d7de4d982720a02fb52174" +
"105f971eda15e1c9a8912bffdaf70214893ee7eaf6635874fa633885dde419d1" +
"24982675705f34b7778cb6e84a3b3c48fb39f741a241353ce3c290385ea1a12d" +
"db0c1f8fee7dfcf4022c631346ef9679638ffb9be83ba1f5f1f9c0fdc240b2b0" +
"d86edfde8a1d8965ad04cd7a27ea17983010c1a724e0b1a6d895a674b6081c48" +
"17ee7a2b86e9d44417cf42040379b3a6dcf7bf9d1d43a441df8cb53b69e475ac" +
"b9d6e38980db01d3b9359e8111e83b1053bb8d9e6e8d82479dcc174e49fe3b2a" +
"4ca21c6dec70154a558e4cebf785a0e6f95dca0548a02d4d33bf1b581c41ee4e" +
"9ca87109bc90dd40992b93542897d5fa99b3caded8fec936a78d83676a4e12cd" +
"1215237886ca1fad9a0327bdc0cff9a09c0d554ba00f7ef46769c16d9cb9530b" +
"2f45b3da63f5bfecadfbdb1b494ba863d560c4b49c0988ca889a12c50df8044f" +
"50660bb544d4f5aae1b295d2fbd5ceb1bbbaa7864787eebfd6f9d46e18b154a4" +
"789e008ed16e459d0955e741a139dc14f686b5d75bf75216175ac373c90f6ee6" +
"184b47e8d5135ce7d6a74e4f4359337f945d84aa344c9765fdccb13d93205d92" +
"fa567fcb2128e6d93bc44c28aaace017c05ff8775d61879fff5ebbe0d7c8df14" +
"523f7d9fead464dc4ec2ef01f82274aff6da8b51a23e0eb279c76d08e0d08c4d" +
"ac5998800388cded1fc5cfb182d67f9f040ae0540498de28da8e87e8992bbcf7" +
"eca49818b7c89b285786190a21f27e566147fffe0d59538baedbdc0f223a554e" +
"c939e48874c6748e0ee64b1af90394815326f008fbd2d341daad587c36c383a3" +
"7eda3f186f3b5e5e734866af6892a5939b14c80378867ba9872c4a06692eb24f" +
"6d22d0c0ac0ab363702a06854df05372ca3392b1f8ed8e83eb7d468057284f62" +
"89dbd6b06b435d5ab3e670483024383138ce11ec5dcb8b3f9eee914bc3779cb5" +
"240d1ee4648698d25a074e4b70244d601e542fa3731dfa7c79c4f5fbc0a9c9b3" +
"16450342a8b0260607be5e134782afcc4db8c9e45bfbf18968f581d03148a15b" +
"f203a668f557567bd05b72bb982abcb929d3bb0c72042f53a01dfb7361777edd" +
"3d8511408d1de9cbc65f1461c7993ba2dd686ab3f38923c480f45fe79f3dfda0" +
"6747d74342c4b5c26fd9ad0865c6b57bdaedbb044844b60b76b357ae719ea23a" +
"60c7e0b51c0fc06ece311335bb16060637313263d68d5e4cf152c717e9d65386" +
"903efa1194196f38e093ea4b595ca0dce6d67d8e9bb79dda12d8ac9cce957898" +
"c6c59bba22db8a5d193b9ffb785ff0e2eb682ff588654144500e0a30479604a2" +
"860b8399342d0010c0e136c9441c3ac96375da9037098fff094fc0a0d807a35c" +
"bd1878c0e5768ed09c1e122d6b5231ec4e37eea6a357af1d4fec247de6060e39" +
"a709ba9877f70b185fcf01ff5f2cf8eec09707369d511390810c69f865e53e72" +
"4cc2c321df00680225ae9687e82d89524e363026d53d78ab63f599f2ad2ae7ca" +
"bd37a2bf63fd16f11203fbc056e2cad470761f5acd29c78c25ca14eff7fc9548" +
"d816dd63e22300a92a7e3fb73c04c6062e476f7948e7b8251f5205ccae7163a4" +
"ba48595f6002f6b43156d4ece76d60d7bba0883510ea61375a4c50349f717338" +
"69778e41df56063730b69f599b8592a8144e119cb266a74ad59351ac0487243a" +
"a720a0e9759957bdb84a17fafbf14b64b955182e9fdbd1577276064adb03eb9e" +
"cf7fc220a306ee29927a08773a288a53fc399cbf1a60b91888fcc3a2e4a040c2" +
"fc174848263de5e6f0372b73d6f3f8f4a1e8139e76d1402fc40c33bd3475a31c" +
"bf9bb8ce74cdf96c20c3c5b01f17a87be43f855f976bb1180d3e52df9f273eab" +
"832b93a58736568ad1f835164029df949187bff7d59b4947394fc4e8e695857e" +
"fb413d46f980262ab3869cfcdf966f7cf0f0012b70ce20a0603102a495b34a43" +
"d088fc3911508c67b985be209d5e5720b9e9d4d98c145952a1aa4362caf53fce";
#region Properties
[Fact]
public static void HkdfProperties()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
Assert.True(a.PseudorandomKeySize > 0);
Assert.True(a.MaxCount > 0);
}
[Fact]
public static void Properties()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
Assert.Equal(8160, a.MaxCount);
Assert.Equal(32, a.PseudorandomKeySize);
Assert.Equal(0, a.MinSaltSize);
Assert.Equal(int.MaxValue, a.MaxSaltSize);
}
#endregion
#region Extract #1
[Fact]
public static void ExtractSuccess()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_prkForEmpty.DecodeHex();
var actual = a.Extract(ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty);
Assert.Equal(expected, actual);
Assert.Equal(a.PseudorandomKeySize, actual.Length);
}
#endregion
#region Extract #2
[Fact]
public static void ExtractWithSpanSuccess()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_prkForEmpty.DecodeHex();
var actual = new byte[expected.Length];
a.Extract(ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
#endregion
#region Expand #1
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(17)]
[InlineData(31)]
[InlineData(32)]
[InlineData(63)]
[InlineData(64)]
[InlineData(100)]
public static void ExpandWithCountSuccess(int count)
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex().Substring(..count);
var actual = a.Expand(s_prkForEmpty.DecodeHex(), ReadOnlySpan<byte>.Empty, count);
Assert.NotNull(actual);
Assert.Equal(expected, actual);
Assert.Equal(count, actual.Length);
}
[Fact]
public static void ExpandWithMaxCount()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex();
var actual = a.Expand(s_prkForEmpty.DecodeHex(), ReadOnlySpan<byte>.Empty, a.MaxCount);
Assert.NotNull(actual);
Assert.Equal(expected, actual);
Assert.Equal(a.MaxCount, actual.Length);
}
[Fact]
public static void ExpandWithCountWithLongPrk()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var b = a.Expand((s_prkForEmpty + s_prkForEmpty).DecodeHex(), ReadOnlySpan<byte>.Empty, 256);
Assert.NotNull(b);
Assert.Equal(256, b.Length);
}
#endregion
#region Expand #2
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(17)]
[InlineData(31)]
[InlineData(32)]
[InlineData(63)]
[InlineData(64)]
[InlineData(100)]
public static void ExpandWithSpanSuccess(int count)
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex().Substring(..count);
var actual = new byte[count];
a.Expand(s_prkForEmpty.DecodeHex(), ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
[Fact]
public static void ExpandWithMaxSpan()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex();
var actual = new byte[a.MaxCount];
a.Expand(s_prkForEmpty.DecodeHex(), ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
[Fact]
public static void ExpandWithSpanWithLongPrk()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var b = new byte[256];
a.Expand((s_prkForEmpty + s_prkForEmpty).DecodeHex(), ReadOnlySpan<byte>.Empty, b);
Assert.NotNull(b);
Assert.Equal(256, b.Length);
}
#endregion
#region DeriveBytes #1
[Fact]
public static void DeriveBytesEmpty()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex();
var actual = a.DeriveBytes(ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, a.MaxCount);
Assert.NotNull(actual);
Assert.Equal(expected, actual);
Assert.Equal(a.MaxCount, actual.Length);
}
#endregion
#region DeriveBytes #2
[Fact]
public static void DeriveBytesWithSpanEmpty()
{
var a = KeyDerivationAlgorithm.HkdfSha256;
var expected = s_outputForEmpty.DecodeHex();
var actual = new byte[a.MaxCount];
a.DeriveBytes(ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
#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;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading.Tasks;
namespace System.Xml
{
internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
// Returns the text value of the current node.
public override Task<string> GetValueAsync()
{
return _coreReader.GetValueAsync();
}
// Reads and validated next node from the input data
public override async Task<bool> ReadAsync()
{
switch (_parsingFunction)
{
case ParsingFunction.Read:
if (await _coreReader.ReadAsync().ConfigureAwait(false))
{
ProcessCoreReaderEvent();
return true;
}
else
{
_validator.CompleteValidation();
return false;
}
case ParsingFunction.ParseDtdFromContext:
_parsingFunction = ParsingFunction.Read;
await ParseDtdFromParserContextAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
case ParsingFunction.Error:
case ParsingFunction.ReaderClosed:
return false;
case ParsingFunction.Init:
_parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState
if (_coreReader.ReadState == ReadState.Interactive)
{
ProcessCoreReaderEvent();
return true;
}
else
{
goto case ParsingFunction.Read;
}
case ParsingFunction.ResolveEntityInternally:
_parsingFunction = ParsingFunction.Read;
await ResolveEntityInternallyAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
case ParsingFunction.InReadBinaryContent:
_parsingFunction = ParsingFunction.Read;
await _readBinaryHelper.FinishAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
default:
Debug.Assert(false);
return false;
}
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
internal async Task MoveOffEntityReferenceAsync()
{
if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally)
{
if (!await _outerReader.ReadAsync().ConfigureAwait(false))
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
}
// Returns typed value of the current node (based on the type specified by schema)
public async Task<object> ReadTypedValueAsync()
{
if (_validationType == ValidationType.None)
{
return null;
}
switch (_outerReader.NodeType)
{
case XmlNodeType.Attribute:
return _coreReaderImpl.InternalTypedValue;
case XmlNodeType.Element:
if (SchemaType == null)
{
return null;
}
XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype;
if (dtype != null)
{
if (!_outerReader.IsEmptyElement)
{
for (;;)
{
if (!await _outerReader.ReadAsync().ConfigureAwait(false))
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
XmlNodeType type = _outerReader.NodeType;
if (type != XmlNodeType.CDATA && type != XmlNodeType.Text &&
type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace &&
type != XmlNodeType.Comment && type != XmlNodeType.ProcessingInstruction)
{
break;
}
}
if (_outerReader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString());
}
}
return _coreReaderImpl.InternalTypedValue;
}
return null;
case XmlNodeType.EndElement:
return null;
default:
if (_coreReaderImpl.V1Compat)
{ //If v1 XmlValidatingReader return null
return null;
}
else
{
return await GetValueAsync().ConfigureAwait(false);
}
}
}
//
// Private implementation methods
//
private async Task ParseDtdFromParserContextAsync()
{
Debug.Assert(_parserContext != null);
Debug.Assert(_coreReaderImpl.DtdInfo == null);
if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0)
{
return;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(_coreReaderImpl);
IDtdInfo dtdInfo = await dtdParser.ParseFreeFloatingDtdAsync(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId, _parserContext.SystemId, _parserContext.InternalSubset, proxy).ConfigureAwait(false);
_coreReaderImpl.SetDtdInfo(dtdInfo);
ValidateDtd();
}
private async Task ResolveEntityInternallyAsync()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference);
int initialDepth = _coreReader.Depth;
_outerReader.ResolveEntity();
while (await _outerReader.ReadAsync().ConfigureAwait(false) && _coreReader.Depth > initialDepth) ;
}
}
}
| |
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide
//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats
//#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
//#define POOLING //Currently using a build setting for this one (also it's experimental)
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
/*
* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class
* for use with Unity
* Copyright Matt Schoen 2010 - 2013
*
*
*
*
* The changes from the original version are under this license:
*
* Copyright (C) 2012-2014 Soomla Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace SoomlaWpCore.util
{
public class JSONObject : NullCheckable,IEnumerable<JSONObject>
{
#if POOLING
const int MAX_POOL_SIZE = 10000;
public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>();
#endif
const int MAX_DEPTH = 100;
const string INFINITY = "\"INFINITY\"";
const string NEGINFINITY = "\"NEGINFINITY\"";
const string NaN = "\"NaN\"";
static readonly char[] WHITESPACE = new[] { ' ', '\r', '\n', '\t' };
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED }
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
public Type type = Type.NULL;
public int Count
{
get
{
if (list == null)
return -1;
return list.Count;
}
}
public List<JSONObject> list;
public List<string> keys;
public string str;
#if USEFLOAT
public float n;
public float f
{
get
{
return n;
}
}
#else
public double n;
public float f {
get {
return (float)n;
}
}
#endif
public bool b;
public delegate void AddJSONConents(JSONObject self);
public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object
public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object
public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array
public JSONObject(Type t)
{
type = t;
switch (t)
{
case Type.ARRAY:
list = new List<JSONObject>();
break;
case Type.OBJECT:
list = new List<JSONObject>();
keys = new List<string>();
break;
}
}
public JSONObject(bool b)
{
type = Type.BOOL;
this.b = b;
}
#if USEFLOAT
public JSONObject(float f)
{
type = Type.NUMBER;
n = f;
}
#else
public JSONObject(double d) {
type = Type.NUMBER;
n = d;
}
#endif
public JSONObject(Dictionary<string, string> dic)
{
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach (KeyValuePair<string, string> kvp in dic)
{
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dic)
{
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach (KeyValuePair<string, JSONObject> kvp in dic)
{
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONConents content)
{
content.Invoke(this);
}
public JSONObject(JSONObject[] objs)
{
type = Type.ARRAY;
list = new List<JSONObject>(objs);
}
//Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
public static JSONObject StringObject(string val) { return CreateStringObject(val); }
public void Absorb(JSONObject obj)
{
list.AddRange(obj.list);
keys.AddRange(obj.keys);
str = obj.str;
n = obj.n;
b = obj.b;
type = obj.type;
}
public static JSONObject Create()
{
#if POOLING
JSONObject result = null;
while(result == null && releaseQueue.Count > 0) {
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.Log("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.Log("wtflist " + result.list.Count);
#endif
}
if(result != null)
return result;
#endif
return new JSONObject();
}
public static JSONObject Create(Type t)
{
JSONObject obj = Create();
obj.type = t;
switch (t)
{
case Type.ARRAY:
obj.list = new List<JSONObject>();
break;
case Type.OBJECT:
obj.list = new List<JSONObject>();
obj.keys = new List<string>();
break;
}
return obj;
}
public static JSONObject Create(bool val)
{
JSONObject obj = Create();
obj.type = Type.BOOL;
obj.b = val;
return obj;
}
public static JSONObject Create(float val)
{
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(int val)
{
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(double val)
{
JSONObject obj = Create();
obj.type = Type.NUMBER;
#if !USEFLOAT
double tmpValue = val;
#endif
#if USEFLOAT
if(val>float.MaxValue || val <float.MinValue)
{
throw new Exception("JSONObject double exceed float max value");
}
float tmpValue = (float)val;
#endif
obj.n = tmpValue;
return obj;
}
public static JSONObject CreateStringObject(string val)
{
if (!string.IsNullOrEmpty(val))
{
val = EncodeJsString(val);
}
JSONObject obj = Create();
obj.type = Type.STRING;
obj.str = val;
return obj;
}
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
public static JSONObject CreateBakedObject(string val)
{
JSONObject bakedObject = Create();
bakedObject.type = Type.BAKED;
bakedObject.str = val;
return bakedObject;
}
/// <summary>
/// Create a JSONObject by parsing string data
/// </summary>
/// <param name="val">The string to be parsed</param>
/// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level,
/// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully
/// parse "a string" into a string-type </param>
/// <returns></returns>
public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false)
{
JSONObject obj = Create();
obj.Parse(val, maxDepth, storeExcessLevels, strict);
return obj;
}
public static JSONObject Create(AddJSONConents content)
{
JSONObject obj = Create();
content.Invoke(obj);
return obj;
}
public static JSONObject Create(Dictionary<string, string> dic)
{
JSONObject obj = Create();
obj.type = Type.OBJECT;
obj.keys = new List<string>();
obj.list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach (KeyValuePair<string, string> kvp in dic)
{
obj.keys.Add(kvp.Key);
obj.list.Add(CreateStringObject(kvp.Value));
}
return obj;
}
public JSONObject() { }
#region PARSE
public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false)
{ //create a new JSONObject from a string (this will also create any children, and parse the whole string)
Parse(str, maxDepth, storeExcessLevels, strict);
}
void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false)
{
if (!string.IsNullOrEmpty(str))
{
str = str.Trim(WHITESPACE);
if (strict)
{
if (str[0] != '[' && str[0] != '{')
{
type = Type.NULL;
SoomlaUtils.LogError(TAG,"Improper (strict) JSON formatting. First character must be [ or {");
return;
}
}
if (str.Length > 0)
{
if (str.ToLower() == "true")
{
type = Type.BOOL;
b = true;
}
else if (str.ToLower() == "false")
{
type = Type.BOOL;
b = false;
}
else if (str.ToLower() == "null")
{
type = Type.NULL;
#if USEFLOAT
}
else if (str == INFINITY)
{
type = Type.NUMBER;
n = float.PositiveInfinity;
}
else if (str == NEGINFINITY)
{
type = Type.NUMBER;
n = float.NegativeInfinity;
}
else if (str == NaN)
{
type = Type.NUMBER;
n = float.NaN;
#else
} else if(str == INFINITY) {
type = Type.NUMBER;
n = double.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = double.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = double.NaN;
#endif
}
else if (str[0] == '"')
{
type = Type.STRING;
this.str = Regex.Unescape(str.Substring(1, str.Length - 2));
}
else
{
int tokenTmp = 1;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
int offset = 0;
switch (str[offset])
{
case '{':
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
break;
case '[':
type = Type.ARRAY;
list = new List<JSONObject>();
break;
default:
try
{
#if USEFLOAT
n = System.Convert.ToSingle(str,CultureInfo.InvariantCulture);
#else
n = System.Convert.ToDouble(str, CultureInfo.InvariantCulture);
#endif
type = Type.NUMBER;
}
catch (System.FormatException)
{
type = Type.NULL;
SoomlaUtils.LogError(TAG,"improper JSON formatting:" + str);
}
return;
}
string propName = "";
bool openQuote = false;
bool inProp = false;
int depth = 0;
while (++offset < str.Length)
{
if (System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
continue;
if (str[offset] == '\\')
{
offset += 1;
continue;
}
if (str[offset] == '"')
{
if (openQuote)
{
if (!inProp && depth == 0 && type == Type.OBJECT)
propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
openQuote = false;
}
else
{
if (depth == 0 && type == Type.OBJECT)
tokenTmp = offset;
openQuote = true;
}
}
if (openQuote)
continue;
if (type == Type.OBJECT && depth == 0)
{
if (str[offset] == ':')
{
tokenTmp = offset + 1;
inProp = true;
}
}
if (str[offset] == '[' || str[offset] == '{')
{
depth++;
}
else if (str[offset] == ']' || str[offset] == '}')
{
depth--;
}
//if (encounter a ',' at top level) || a closing ]/}
if ((str[offset] == ',' && depth == 0) || depth < 0)
{
inProp = false;
string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
if (inner.Length > 0)
{
if (type == Type.OBJECT)
keys.Add(propName);
if (maxDepth != -1) //maxDepth of -1 is the end of the line
list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
else if (storeExcessLevels)
list.Add(CreateBakedObject(inner));
}
tokenTmp = offset + 1;
}
}
}
}
else type = Type.NULL;
}
else type = Type.NULL; //If the string is missing, this is a null
//Profiler.EndSample();
}
#endregion
public bool IsNumber { get { return type == Type.NUMBER; } }
public bool IsNull { get { return type == Type.NULL; } }
public bool IsString { get { return type == Type.STRING; } }
public bool IsBool { get { return type == Type.BOOL; } }
public bool IsArray { get { return type == Type.ARRAY; } }
public bool IsObject { get { return type == Type.OBJECT; } }
public void Add(bool val)
{
Add(Create(val));
}
public void Add(float val)
{
Add(Create(val));
}
public void Add(int val)
{
Add(Create(val));
}
public void Add(string str)
{
Add(CreateStringObject(str));
}
public void Add(AddJSONConents content)
{
Add(Create(content));
}
public void Add(JSONObject obj)
{
if (obj)
{ //Don't do anything if the object is null
if (type != Type.ARRAY)
{
type = Type.ARRAY; //Congratulations, son, you're an ARRAY now
if (list == null)
list = new List<JSONObject>();
}
list.Add(obj);
}
}
public void AddField(string name, bool val)
{
AddField(name, Create(val));
}
public void AddField(string name, float val)
{
AddField(name, Create(val));
}
public void AddField(string name, int val)
{
AddField(name, Create(val));
}
public void AddField(string name, double val)
{
AddField(name, Create(val));
}
public void AddField(string name, AddJSONConents content)
{
AddField(name, Create(content));
}
public void AddField(string name, string val)
{
AddField(name, CreateStringObject(val));
}
public void AddField(string name, JSONObject obj)
{
if (obj)
{ //Don't do anything if the object is null
if (type != Type.OBJECT)
{
if (keys == null)
keys = new List<string>();
if (type == Type.ARRAY)
{
for (int i = 0; i < list.Count; i++)
keys.Add(i + "");
}
else
if (list == null)
list = new List<JSONObject>();
type = Type.OBJECT; //Congratulations, son, you're an OBJECT now
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, bool val) { SetField(name, Create(val)); }
public void SetField(string name, float val) { SetField(name, Create(val)); }
public void SetField(string name, int val) { SetField(name, Create(val)); }
public void SetField(string name, string val)
{
SetField(name, CreateStringObject(val));
}
public void SetField(string name, JSONObject obj)
{
if (HasField(name))
{
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public void RemoveField(string name)
{
if (keys.IndexOf(name) > -1)
{
list.RemoveAt(keys.IndexOf(name));
keys.Remove(name);
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject obj);
public void GetField(ref bool field, string name, FieldNotFound fail = null)
{
if (type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
field = list[index].b;
return;
}
}
if (fail != null) fail.Invoke(name);
}
#if USEFLOAT
public void GetField(ref float field, string name, FieldNotFound fail = null)
{
#else
public void GetField(ref double field, string name, FieldNotFound fail = null) {
#endif
if (type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
field = list[index].n;
return;
}
}
if (fail != null) fail.Invoke(name);
}
public void GetField(ref int field, string name, FieldNotFound fail = null)
{
if (type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
field = (int)list[index].n;
return;
}
}
if (fail != null) fail.Invoke(name);
}
public void GetField(ref uint field, string name, FieldNotFound fail = null)
{
if (type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
field = (uint)list[index].n;
return;
}
}
if (fail != null) fail.Invoke(name);
}
public void GetField(ref string field, string name, FieldNotFound fail = null)
{
if (type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
field = list[index].str;
return;
}
}
if (fail != null) fail.Invoke(name);
}
public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null)
{
if (response != null && type == Type.OBJECT)
{
int index = keys.IndexOf(name);
if (index >= 0)
{
response.Invoke(list[index]);
return;
}
}
if (fail != null) fail.Invoke(name);
}
public JSONObject GetField(string name)
{
if (type == Type.OBJECT)
for (int i = 0; i < keys.Count; i++)
if (keys[i] == name)
return list[i];
return null;
}
public bool HasFields(string[] names)
{
for (int i = 0; i < names.Length; i++)
if (!keys.Contains(names[i]))
return false;
return true;
}
public bool HasField(string name)
{
if (type == Type.OBJECT)
for (int i = 0; i < keys.Count; i++)
if (keys[i] == name)
return true;
return false;
}
public void Clear()
{
type = Type.NULL;
if (list != null)
list.Clear();
if (keys != null)
keys.Clear();
str = "";
n = 0;
b = false;
}
/// <summary>
/// Copy a JSONObject. This could probably work better
/// </summary>
/// <returns></returns>
public JSONObject Copy()
{
return Create(Print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj)
{
MergeRecur(this, obj);
}
/// <summary>
/// Merge object right into left recursively
/// </summary>
/// <param name="left">The left (base) object</param>
/// <param name="right">The right (new) object</param>
static void MergeRecur(JSONObject left, JSONObject right)
{
if (left.type == Type.NULL)
left.Absorb(right);
else if (left.type == Type.OBJECT && right.type == Type.OBJECT)
{
for (int i = 0; i < right.list.Count; i++)
{
string key = right.keys[i];
if (right[i].isContainer)
{
if (left.HasField(key))
MergeRecur(left[key], right[i]);
else
left.AddField(key, right[i]);
}
else
{
if (left.HasField(key))
left.SetField(key, right[i]);
else
left.AddField(key, right[i]);
}
}
}
else if (left.type == Type.ARRAY && right.type == Type.ARRAY)
{
if (right.Count > left.Count)
{
SoomlaUtils.LogError(TAG,"Cannot merge arrays when right object has more elements");
return;
}
for (int i = 0; i < right.list.Count; i++)
{
if (left[i].type == right[i].type)
{ //Only overwrite with the same type
if (left[i].isContainer)
MergeRecur(left[i], right[i]);
else
{
left[i] = right[i];
}
}
}
}
}
public void Bake()
{
if (type != Type.BAKED)
{
str = Print();
type = Type.BAKED;
}
}
public IEnumerable BakeAsync()
{
if (type != Type.BAKED)
{
foreach (string s in PrintAsync())
{
if (s == null)
yield return s;
else
{
str = s;
}
}
type = Type.BAKED;
}
}
#pragma warning disable 219
public string print(bool pretty = false)
{
return Print(pretty);
}
public string Print(bool pretty = false)
{
StringBuilder builder = new StringBuilder();
Stringify(0, builder, pretty);
return builder.ToString();
}
public IEnumerable<string> PrintAsync(bool pretty = false)
{
StringBuilder builder = new StringBuilder();
printWatch.Reset();
printWatch.Start();
foreach (IEnumerable e in StringifyAsync(0, builder, pretty))
{
yield return null;
}
yield return builder.ToString();
}
#pragma warning restore 219
#region STRINGIFY
const float maxFrameTime = 0.008f;
static readonly Stopwatch printWatch = new Stopwatch();
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false)
{ //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if (depth++ > MAX_DEPTH)
{
SoomlaUtils.LogDebug(TAG,"reached max depth!");
yield break;
}
if (printWatch.Elapsed.TotalSeconds > maxFrameTime)
{
printWatch.Reset();
yield return null;
printWatch.Start();
}
switch (type)
{
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if (float.IsInfinity(n))
builder.Append(INFINITY);
else if (float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if (float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if (list.Count > 0)
{
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if (pretty)
builder.Append("\n");
#endif
for (int i = 0; i < list.Count; i++)
{
string key = keys[i];
JSONObject obj = list[i];
if (obj)
{
#if(PRETTY)
if (pretty)
for (int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
foreach (IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if (pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if (pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if (pretty && list.Count > 0)
{
builder.Append("\n");
for (int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if (list.Count > 0)
{
#if(PRETTY)
if (pretty)
builder.Append("\n"); //for a bit more readability
#endif
for (int i = 0; i < list.Count; i++)
{
if (list[i])
{
#if(PRETTY)
if (pretty)
for (int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
foreach (IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if (pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if (pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if (pretty && list.Count > 0)
{
builder.Append("\n");
for (int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if (b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
//TODO: Refactor Stringify functions to share core logic
/*
* I know, I know, this is really bad form. It turns out that there is a
* significant amount of garbage created when calling as a coroutine, so this
* method is duplicated. Hopefully there won't be too many future changes, but
* I would still like a more elegant way to optionaly yield
*/
void Stringify(int depth, StringBuilder builder, bool pretty = false)
{ //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if (depth++ > MAX_DEPTH)
{
SoomlaUtils.LogDebug(TAG,"reached max depth!");
return;
}
switch (type)
{
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if (float.IsInfinity(n))
builder.Append(INFINITY);
else if (float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if (float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString("0.##########",CultureInfo.InvariantCulture));
break;
case Type.OBJECT:
builder.Append("{");
if (list.Count > 0)
{
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if (pretty)
builder.Append("\n");
#endif
for (int i = 0; i < list.Count; i++)
{
string key = keys[i];
JSONObject obj = list[i];
if (obj)
{
#if(PRETTY)
if (pretty)
for (int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
obj.Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if (pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if (pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if (pretty && list.Count > 0)
{
builder.Append("\n");
for (int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if (list.Count > 0)
{
#if(PRETTY)
if (pretty)
builder.Append("\n"); //for a bit more readability
#endif
for (int i = 0; i < list.Count; i++)
{
if (list[i])
{
#if(PRETTY)
if (pretty)
for (int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
list[i].Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if (pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if (pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if (pretty && list.Count > 0)
{
builder.Append("\n");
for (int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if (b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
#endregion
/*
public static implicit operator WWWForm(JSONObject obj)
{
WWWForm form = new WWWForm();
for (int i = 0; i < obj.list.Count; i++)
{
string key = i + "";
if (obj.type == Type.OBJECT)
key = obj.keys[i];
string val = obj.list[i].ToString();
if (obj.list[i].type == Type.STRING)
val = val.Replace("\"", "");
form.AddField(key, val);
}
return form;
}*/
public JSONObject this[int index]
{
get
{
if (list.Count > index) return list[index];
return null;
}
set
{
if (list.Count > index)
list[index] = value;
}
}
public JSONObject this[string index]
{
get
{
return GetField(index);
}
set
{
SetField(index, value);
}
}
public override string ToString()
{
return Print();
}
public string ToString(bool pretty)
{
return Print(pretty);
}
public Dictionary<string, string> ToDictionary()
{
if (type == Type.OBJECT)
{
Dictionary<string, string> result = new Dictionary<string, string>();
for (int i = 0; i < list.Count; i++)
{
JSONObject val = list[i];
switch (val.type)
{
case Type.STRING: result.Add(keys[i], val.str); break;
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
case Type.BOOL: result.Add(keys[i], val.b + ""); break;
default: SoomlaUtils.LogError(TAG,"Omitting object: " + keys[i] + " in dictionary conversion"); break;
}
}
return result;
}
SoomlaUtils.LogError(TAG,"Tried to turn non-Object JSONObject into a dictionary");
return null;
}
public static implicit operator bool(JSONObject o)
{
return o != null;
}
#if POOLING
static bool pool = true;
public static void ClearPool() {
pool = false;
releaseQueue.Clear();
pool = true;
}
~JSONObject() {
if(pool && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
releaseQueue.Enqueue(this);
}
}
#endif
#region IEnumerable<JSONObject> Members
public IEnumerator<JSONObject> GetEnumerator()
{
foreach (JSONObject jObject in list)
{
// Lets check for end of list (its bad code since we used arrays)
if (jObject == null) // this wont work is T is not a nullable type
{
break;
}
// Return the current element and then on next function call
// resume from next element rather than starting all over again;
yield return jObject;
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
// Lets call the generic version here
return this.GetEnumerator();
}
#endregion
private const String TAG = "SOOMLA Core JSONObject";
}
}
| |
using NUnit.Framework;
using System;
using System.Web;
using System.Text.RegularExpressions;
using Braintree.Exceptions;
using System.Collections.Specialized;
namespace Braintree.Tests
{
//[Ignore("Need fixing")] //TODO: fix unit test
[TestFixture(Category = "NeedFix")] //TODO: fix unit test
public class OAuthTest
{
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway(
"client_id$development$integration_client_id",
"client_secret$development$integration_client_secret"
);
}
[Test]
public void CreateTokenFromCode_ReturnsOAuthCredentials()
{
string code = OAuthTestHelper.CreateGrant(gateway, "integration_merchant_id", "read_write");
ResultImpl<OAuthCredentials> result = gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = code,
Scope = "read_write"
});
Assert.IsTrue(result.IsSuccess());
Assert.IsNotNull(result.Target.AccessToken);
Assert.IsNotNull(result.Target.RefreshToken);
Assert.IsNotNull(result.Target.ExpiresAt);
Assert.AreEqual("bearer", result.Target.TokenType);
}
[Test]
public void CreateTokenFromRefreshToken_ExchangesRefreshTokenForAccessToken()
{
string code = OAuthTestHelper.CreateGrant(gateway, "integration_merchant_id", "read_write");
ResultImpl<OAuthCredentials> accessTokenResult = gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = code,
Scope = "read_write"
});
ResultImpl<OAuthCredentials> refreshTokenResult = gateway.OAuth.CreateTokenFromRefreshToken(new OAuthCredentialsRequest {
RefreshToken = accessTokenResult.Target.RefreshToken,
Scope = "read_write"
});
Assert.IsTrue(refreshTokenResult.IsSuccess());
Assert.IsNotNull(refreshTokenResult.Target.AccessToken);
Assert.IsNotNull(refreshTokenResult.Target.RefreshToken);
Assert.IsNotNull(refreshTokenResult.Target.ExpiresAt);
Assert.AreEqual("bearer", refreshTokenResult.Target.TokenType);
}
[Test]
public void CreateTokenFromBadCode_ReturnsFailureCode()
{
ResultImpl<OAuthCredentials> result = gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = "bad_code",
Scope = "read_write"
});
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.OAUTH_INVALID_GRANT,
result.Errors.ForObject("Credentials").OnField("Code")[0].Code
);
Assert.AreEqual(
"Invalid grant: code not found",
result.Errors.ForObject("Credentials").OnField("Code")[0].Message
);
}
[Test]
public void CreateTokenFromCode_RaisesIfWrongCredentials()
{
try {
gateway = new BraintreeGateway(
"access_token$development$merchant_id$_oops_this_is_not_a_client_id_and_secret"
);
gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest());
Assert.Fail("Should throw ConfigurationException");
} catch (ConfigurationException) {}
}
[Test]
public void ConnectUrl_ReturnsCorrectUrl()
{
string url = gateway.OAuth.ConnectUrl(new OAuthConnectUrlRequest {
MerchantId = "integration_merchant_id",
RedirectUri = "http://bar.example.com",
Scope = "read_write",
State = "baz_state",
User = new OAuthConnectUrlUserRequest {
Country = "USA",
Email = "[email protected]",
FirstName = "Bob",
LastName = "Jones",
Phone = "555-555-5555",
DobYear = "1970",
DobMonth = "01",
DobDay = "01",
StreetAddress = "222 W Merchandise Mart",
Locality = "Chicago",
Region = "IL",
PostalCode = "60606",
},
Business = new OAuthConnectUrlBusinessRequest {
Name = "14 Ladders",
RegisteredAs = "14.0 Ladders",
Industry = "Ladders",
Description = "We sell the best ladders",
StreetAddress = "111 N Canal",
Locality = "Chicago",
Region = "IL",
PostalCode = "60606",
Country = "USA",
AnnualVolumeAmount = "1000000",
AverageTransactionAmount = "100",
MaximumTransactionAmount = "10000",
ShipPhysicalGoods = true,
FulfillmentCompletedIn = 7,
Currency = "USD",
Website = "http://example.com",
},
});
var uri = new Uri(url);
NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);
Assert.AreEqual("localhost", uri.Host);
Assert.AreEqual("/oauth/connect", uri.AbsolutePath);
Assert.AreEqual("integration_merchant_id", query["merchant_id"]);
Assert.AreEqual("client_id$development$integration_client_id", query["client_id"]);
Assert.AreEqual("http://bar.example.com", query["redirect_uri"]);
Assert.AreEqual("read_write", query["scope"]);
Assert.AreEqual("baz_state", query["state"]);
Assert.AreEqual("USA", query["user[country]"]);
Assert.AreEqual("[email protected]", query["user[email]"]);
Assert.AreEqual("Bob", query["user[first_name]"]);
Assert.AreEqual("Jones", query["user[last_name]"]);
Assert.AreEqual("555-555-5555", query["user[phone]"]);
Assert.AreEqual("1970", query["user[dob_year]"]);
Assert.AreEqual("01", query["user[dob_month]"]);
Assert.AreEqual("01", query["user[dob_day]"]);
Assert.AreEqual("222 W Merchandise Mart", query["user[street_address]"]);
Assert.AreEqual("Chicago", query["user[locality]"]);
Assert.AreEqual("IL", query["user[region]"]);
Assert.AreEqual("60606", query["user[postal_code]"]);
Assert.AreEqual("14 Ladders", query["business[name]"]);
Assert.AreEqual("14.0 Ladders", query["business[registered_as]"]);
Assert.AreEqual("Ladders", query["business[industry]"]);
Assert.AreEqual("We sell the best ladders", query["business[description]"]);
Assert.AreEqual("111 N Canal", query["business[street_address]"]);
Assert.AreEqual("Chicago", query["business[locality]"]);
Assert.AreEqual("IL", query["business[region]"]);
Assert.AreEqual("60606", query["business[postal_code]"]);
Assert.AreEqual("USA", query["business[country]"]);
Assert.AreEqual("1000000", query["business[annual_volume_amount]"]);
Assert.AreEqual("100", query["business[average_transaction_amount]"]);
Assert.AreEqual("10000", query["business[maximum_transaction_amount]"]);
Assert.AreEqual("true", query["business[ship_physical_goods]"]);
Assert.AreEqual("7", query["business[fulfillment_completed_in]"]);
Assert.AreEqual("USD", query["business[currency]"]);
Assert.AreEqual("http://example.com", query["business[website]"]);
Assert.AreEqual(64, query["signature"].Length);
var hexRegex = new Regex("^[a-f0-9]+$");
Assert.IsTrue(hexRegex.IsMatch(query["signature"]));
Assert.AreEqual("SHA256", query["algorithm"]);
}
[Test]
public void ConnectUrl_WorksWithoutOptionalParameters()
{
string url = gateway.OAuth.ConnectUrl(new OAuthConnectUrlRequest());
var uri = new Uri(url);
NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);
Assert.IsNull(query["redirect_uri"]);
}
[Test]
public void ConnectUrl_WorksWithMultiplePaymentMethods()
{
string url = gateway.OAuth.ConnectUrl(new OAuthConnectUrlRequest {
PaymentMethods = new string[] {"credit_card", "paypal"}
});
var uri = new Uri(url);
NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);
Assert.AreEqual("credit_card,paypal", query["payment_methods[]"]);
}
[Test]
public void ComputeSignature_ReturnsCorrectSignature()
{
string url = "http://localhost:3000/oauth/connect?business%5Bname%5D=We+Like+Spaces&client_id=client_id%24development%24integration_client_id";
string signature = gateway.OAuth.ComputeSignature(url);
Assert.AreEqual("a36bcf10dd982e2e47e0d6a2cb930aea47ade73f954b7d59c58dae6167894d41", signature);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
namespace System.Linq.Expressions
{
/// <summary>
/// Specifies what kind of jump this <see cref="GotoExpression"/> represents.
/// </summary>
public enum GotoExpressionKind
{
/// <summary>
/// A <see cref="GotoExpression"/> that represents a jump to some location.
/// </summary>
Goto,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a return statement.
/// </summary>
Return,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a break statement.
/// </summary>
Break,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a continue statement.
/// </summary>
Continue,
}
/// <summary>
/// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps.
/// </summary>
[DebuggerTypeProxy(typeof(GotoExpressionProxy))]
public sealed class GotoExpression : Expression
{
internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type)
{
Kind = kind;
Value = value;
Target = target;
Type = type;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type { get; }
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.Goto;
/// <summary>
/// The value passed to the target, or null if the target is of type
/// System.Void.
/// </summary>
public Expression Value { get; }
/// <summary>
/// The target label where this node jumps to.
/// </summary>
public LabelTarget Target { get; }
/// <summary>
/// The kind of the goto. For information purposes only.
/// </summary>
public GotoExpressionKind Kind { get; }
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitGoto(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="target">The <see cref="Target"/> property of the result.</param>
/// <param name="value">The <see cref="Value"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public GotoExpression Update(LabelTarget target, Expression value)
{
if (target == Target && value == Value)
{
return this;
}
return Expression.MakeGoto(Kind, target, value, Type);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Break"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target)
{
return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Break"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target, Expression value)
{
return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Break"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and the <see cref="Type"/> property set to <paramref name="type"/>.
/// </returns>
public static GotoExpression Break(LabelTarget target, Type type)
{
return MakeGoto(GotoExpressionKind.Break, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Break"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target, Expression value, Type type)
{
return MakeGoto(GotoExpressionKind.Break, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a continue statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Continue"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Continue(LabelTarget target)
{
return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Continue"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Continue(LabelTarget target, Type type)
{
return MakeGoto(GotoExpressionKind.Continue, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Return"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target)
{
return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Return"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Type type)
{
return MakeGoto(GotoExpressionKind.Return, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Return"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Expression value)
{
return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Return"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Expression value, Type type)
{
return MakeGoto(GotoExpressionKind.Return, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Goto"/>,
/// the <see cref="GotoExpression.Target"/> property set to the specified value,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target)
{
return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Goto"/>,
/// the <see cref="GotoExpression.Target"/> property set to the specified value,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Type type)
{
return MakeGoto(GotoExpressionKind.Goto, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Goto"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Expression value)
{
return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <see cref="GotoExpressionKind.Goto"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Expression value, Type type)
{
return MakeGoto(GotoExpressionKind.Goto, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>.
/// The value passed to the label upon jumping can also be specified.
/// </summary>
/// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">A <see cref="System.Type"/> to set the <see cref="Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="GotoExpression.Kind"/> equal to <paramref name="kind"/>,
/// the <see cref="GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type)
{
ValidateGoto(target, ref value, nameof(target), nameof(value), type);
return new GotoExpression(kind, target, value, type);
}
private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter, Type type)
{
ContractUtils.RequiresNotNull(target, targetParameter);
if (value == null)
{
if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(nameof(target));
if (type != null)
{
TypeUtils.ValidateType(type, nameof(type));
}
}
else
{
ValidateGotoType(target.Type, ref value, valueParameter);
}
}
// Standard argument validation, taken from ValidateArgumentTypes
private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName)
{
ExpressionUtils.RequiresCanRead(value, paramName);
if (expectedType != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type))
{
// C# auto-quotes return values, so we'll do that here
if (!TryQuote(expectedType, ref value))
{
throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.IO;
/// <summary>
/// FileSystemOperations operations.
/// </summary>
public partial interface IFileSystemOperations
{
/// <summary>
/// Test the existence of a file or directory object specified by the file path.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='getFilePath'>
/// The Data Lake Store path (starting with '/') of the file or directory for
/// which to test.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
Task<AzureOperationResponse<bool>> PathExistsWithHttpMessagesAsync(string accountName, string getFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Uploads a folder to the specified Data Lake Store account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='sourcePath'>
/// The local source folder to upload to the Data Lake Store account.
/// </param>
/// <param name='destinationPath'>
/// The Data Lake Store path (starting with '/') of the directory to upload to.
/// </param>
/// <param name='perFileThreadCount'>
/// The maximum number of threads to use per file during the upload. By default, this number will be computed based on folder structure and average file size.
/// </param>
/// <param name='concurrentFileCount'>
/// The maximum number of files to upload at once. By default, this number will be computed based on folder structure and number of files.
/// </param>
/// <param name='resume'>
/// A switch indicating if this upload is a continuation of a previous, failed upload. Default is false.
/// </param>
/// <param name='overwrite'>
/// A switch indicating this upload should overwrite the contents of the target directory if it exists. Default is false, and the upload will fast fail if the target location exists.
/// </param>
/// <param name='uploadAsBinary'>
/// A switch indicating this upload should treat all data as binary, which is slightly more performant but does not ensure record boundary integrity. This is recommended for large folders of mixed binary and text files or binary only directories. Default is false
/// </param>
/// <param name='recurse'>
/// A switch indicating this upload should upload the source directory recursively or just the top level. Default is false, only the top level will be uploaded.
/// </param>
/// <param name='progressTracker'>
/// An optional delegate that can be used to track the progress of the upload operation asynchronously.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code.
/// </exception>
/// <exception cref="TaskCanceledException">
/// Thrown when the operation takes too long to complete or if the user explicitly cancels it.
/// </exception>
/// <exception cref="InvalidMetadataException">
/// Thrown when resume metadata is corrupt or not associated with the current operation.
/// </exception>
/// <exception cref="FileNotFoundException">
/// Thrown when the source path cannot be found.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if an invalid upload is attempted or a file/folder is modified externally during the operation.
/// </exception>
/// <exception cref="TransferFailedException">
/// Thrown if the transfer operation fails.
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
void UploadFolder(
string accountName,
string sourcePath,
string destinationPath,
int perFileThreadCount = -1,
int concurrentFileCount = -1,
bool resume = false,
bool overwrite = false,
bool uploadAsBinary = false,
bool recurse = false,
IProgress<TransferFolderProgress> progressTracker = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Downloads a folder from the specified Data Lake Store account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='sourcePath'>
/// The Data Lake Store path (starting with '/') of the directory to download.
/// </param>
/// <param name='destinationPath'>
/// The local path to download the folder to.
/// </param>
/// <param name='perFileThreadCount'>
/// The maximum number of threads to use per file during the download. By default, this number will be computed based on folder structure and average file size.
/// </param>
/// <param name='concurrentFileCount'>
/// The maximum number of files to download at once. By default, this number will be computed based on folder structure and number of files.
/// </param>
/// <param name='resume'>
/// A switch indicating if this download is a continuation of a previous, failed download. Default is false.
/// </param>
/// <param name='overwrite'>
/// A switch indicating this download should overwrite the contents of the target directory if it exists. Default is false, and the download will fast fail if the target location exists.
/// </param>
/// <param name='recurse'>
/// A switch indicating this download should download the source directory recursively or just the top level. Default is false, only the top level will be downloaded.
/// </param>
/// <param name='progressTracker'>
/// An optional delegate that can be used to track the progress of the download operation asynchronously.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code.
/// </exception>
/// <exception cref="TaskCanceledException">
/// Thrown when the operation takes too long to complete or if the user explicitly cancels it.
/// </exception>
/// <exception cref="InvalidMetadataException">
/// Thrown when resume metadata is corrupt or not associated with the current operation.
/// </exception>
/// <exception cref="FileNotFoundException">
/// Thrown when the source path cannot be found.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if an invalid download is attempted or a file/folder is modified externally during the operation.
/// </exception>
/// <exception cref="TransferFailedException">
/// Thrown if the transfer operation fails.
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
void DownloadFolder(
string accountName,
string sourcePath,
string destinationPath,
int perFileThreadCount = -1,
int concurrentFileCount = -1,
bool resume = false,
bool overwrite = false,
bool recurse = false,
IProgress<TransferFolderProgress> progressTracker = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Uploads a file to the specified Data Lake Store account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='sourcePath'>
/// The local source file to upload to the Data Lake Store account.
/// </param>
/// <param name='destinationPath'>
/// The Data Lake Store path (starting with '/') of the directory or directory and filename to upload to.
/// </param>
/// <param name='threadCount'>
/// The maximum number of threads to use during the upload. By default, this number will be computed based on file size.
/// </param>
/// <param name='resume'>
/// A switch indicating if this upload is a continuation of a previous, failed upload. Default is false.
/// </param>
/// <param name='overwrite'>
/// A switch indicating this upload should overwrite the target file if it exists. Default is false, and the upload will fast fail if the target file exists.
/// </param>
/// <param name='uploadAsBinary'>
/// A switch indicating this upload should treat the file as binary, which is slightly more performant but does not ensure record boundary integrity.
/// </param>
/// <param name='progressTracker'>
/// An optional delegate that can be used to track the progress of the upload operation asynchronously.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code.
/// </exception>
/// <exception cref="TaskCanceledException">
/// Thrown when the operation takes too long to complete or if the user explicitly cancels it.
/// </exception>
/// <exception cref="InvalidMetadataException">
/// Thrown when resume metadata is corrupt or not associated with the current operation.
/// </exception>
/// <exception cref="FileNotFoundException">
/// Thrown when the source path cannot be found.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if an invalid upload is attempted or the file is modified externally during the operation.
/// </exception>
/// <exception cref="TransferFailedException">
/// Thrown if the transfer operation fails.
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
void UploadFile(
string accountName,
string sourcePath,
string destinationPath,
int threadCount = -1,
bool resume = false,
bool overwrite = false,
bool uploadAsBinary = false,
IProgress<TransferProgress> progressTracker = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Downloads a file from the specified Data Lake Store account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='sourcePath'>
/// The Data Lake Store path (starting with '/') of the file to download.
/// </param>
/// <param name='destinationPath'>
/// The local path to download the file to. If a directory is specified, the file name will be the same as the source file name
/// </param>
/// <param name='threadCount'>
/// The maximum number of threads to use during the download. By default, this number will be computed based on file size.
/// </param>
/// <param name='resume'>
/// A switch indicating if this download is a continuation of a previous, failed download. Default is false.
/// </param>
/// <param name='overwrite'>
/// A switch indicating this download should overwrite the the target file if it exists. Default is false, and the download will fast fail if the target file exists.
/// </param>
/// <param name='progressTracker'>
/// An optional delegate that can be used to track the progress of the download operation asynchronously.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code.
/// </exception>
/// <exception cref="TaskCanceledException">
/// Thrown when the operation takes too long to complete or if the user explicitly cancels it.
/// </exception>
/// <exception cref="InvalidMetadataException">
/// Thrown when resume metadata is corrupt or not associated with the current operation.
/// </exception>
/// <exception cref="FileNotFoundException">
/// Thrown when the source path cannot be found.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if an invalid download is attempted or a file is modified externally during the operation.
/// </exception>
/// <exception cref="TransferFailedException">
/// Thrown if the transfer operation fails.
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
void DownloadFile(
string accountName,
string sourcePath,
string destinationPath,
int threadCount = -1,
bool resume = false,
bool overwrite = false,
IProgress<TransferProgress> progressTracker = null,
CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace YAF.Lucene.Net.Search
{
/*
* 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 AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
using BooleanWeight = YAF.Lucene.Net.Search.BooleanQuery.BooleanWeight;
/// <summary>
/// Description from Doug Cutting (excerpted from
/// LUCENE-1483):
/// <para/>
/// <see cref="BooleanScorer"/> uses an array to score windows of
/// 2K docs. So it scores docs 0-2K first, then docs 2K-4K,
/// etc. For each window it iterates through all query terms
/// and accumulates a score in table[doc%2K]. It also stores
/// in the table a bitmask representing which terms
/// contributed to the score. Non-zero scores are chained in
/// a linked list. At the end of scoring each window it then
/// iterates through the linked list and, if the bitmask
/// matches the boolean constraints, collects a hit. For
/// boolean queries with lots of frequent terms this can be
/// much faster, since it does not need to update a priority
/// queue for each posting, instead performing constant-time
/// operations per posting. The only downside is that it
/// results in hits being delivered out-of-order within the
/// window, which means it cannot be nested within other
/// scorers. But it works well as a top-level scorer.
/// <para/>
/// The new BooleanScorer2 implementation instead works by
/// merging priority queues of postings, albeit with some
/// clever tricks. For example, a pure conjunction (all terms
/// required) does not require a priority queue. Instead it
/// sorts the posting streams at the start, then repeatedly
/// skips the first to to the last. If the first ever equals
/// the last, then there's a hit. When some terms are
/// required and some terms are optional, the conjunction can
/// be evaluated first, then the optional terms can all skip
/// to the match and be added to the score. Thus the
/// conjunction can reduce the number of priority queue
/// updates for the optional terms.
/// </summary>
internal sealed class BooleanScorer : BulkScorer
{
private sealed class BooleanScorerCollector : ICollector
{
private readonly BucketTable bucketTable; // LUCENENET: marked readonly
private readonly int mask; // LUCENENET: marked readonly
private Scorer scorer;
public BooleanScorerCollector(int mask, BucketTable bucketTable)
{
this.mask = mask;
this.bucketTable = bucketTable;
}
public void Collect(int doc)
{
BucketTable table = bucketTable;
int i = doc & BucketTable.MASK;
Bucket bucket = table.buckets[i];
if (bucket.Doc != doc) // invalid bucket
{
bucket.Doc = doc; // set doc
bucket.Score = scorer.GetScore(); // initialize score
bucket.Bits = mask; // initialize mask
bucket.Coord = 1; // initialize coord
bucket.Next = table.first; // push onto valid list
table.first = bucket;
} // valid bucket
else
{
bucket.Score += scorer.GetScore(); // increment score
bucket.Bits |= mask; // add bits in mask
bucket.Coord++; // increment coord
}
}
public void SetNextReader(AtomicReaderContext context)
{
// not needed by this implementation
}
public void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public bool AcceptsDocsOutOfOrder => true;
}
internal sealed class Bucket
{
internal int Doc { get; set; } // tells if bucket is valid
internal double Score { get; set; } // incremental score
// TODO: break out bool anyProhibited, int
// numRequiredMatched; then we can remove 32 limit on
// required clauses
internal int Bits { get; set; } // used for bool constraints
internal int Coord { get; set; } // count of terms in score
internal Bucket Next { get; set; } // next valid bucket
public Bucket()
{
// Initialize properties
Doc = -1;
}
}
/// <summary>
/// A simple hash table of document scores within a range. </summary>
internal sealed class BucketTable
{
public const int SIZE = 1 << 11;
public const int MASK = SIZE - 1;
internal readonly Bucket[] buckets = new Bucket[SIZE];
internal Bucket first = null; // head of valid list
public BucketTable()
{
// Pre-fill to save the lazy init when collecting
// each sub:
for (int idx = 0; idx < SIZE; idx++)
{
buckets[idx] = new Bucket();
}
}
public ICollector NewCollector(int mask)
{
return new BooleanScorerCollector(mask, this);
}
public static int Count => SIZE; // LUCENENET NOTE: This was size() in Lucene. // LUCENENET: CA1822: Mark members as static
}
internal sealed class SubScorer
{
public BulkScorer Scorer { get; set; }
// TODO: re-enable this if BQ ever sends us required clauses
//public boolean required = false;
public bool Prohibited { get; set; }
public ICollector Collector { get; set; }
public SubScorer Next { get; set; }
public bool More { get; set; }
public SubScorer(BulkScorer scorer, bool required, bool prohibited, ICollector collector, SubScorer next)
{
if (required)
{
throw new ArgumentException("this scorer cannot handle required=true");
}
this.Scorer = scorer;
this.More = true;
// TODO: re-enable this if BQ ever sends us required clauses
//this.required = required;
this.Prohibited = prohibited;
this.Collector = collector;
this.Next = next;
}
}
private readonly SubScorer scorers = null; // LUCENENET: marked readonly
private readonly BucketTable bucketTable = new BucketTable(); // LUCENENET: marked readonly
private readonly float[] coordFactors;
// TODO: re-enable this if BQ ever sends us required clauses
//private int requiredMask = 0;
private readonly int minNrShouldMatch;
private int end;
private Bucket current;
// Any time a prohibited clause matches we set bit 0:
private const int PROHIBITED_MASK = 1;
//private readonly Weight weight; // LUCENENET: Never read
internal BooleanScorer(BooleanWeight weight, bool disableCoord, int minNrShouldMatch, IList<BulkScorer> optionalScorers, IList<BulkScorer> prohibitedScorers, int maxCoord)
{
this.minNrShouldMatch = minNrShouldMatch;
//this.weight = weight; // LUCENENET: Never read
foreach (BulkScorer scorer in optionalScorers)
{
scorers = new SubScorer(scorer, false, false, bucketTable.NewCollector(0), scorers);
}
foreach (BulkScorer scorer in prohibitedScorers)
{
scorers = new SubScorer(scorer, false, true, bucketTable.NewCollector(PROHIBITED_MASK), scorers);
}
coordFactors = new float[optionalScorers.Count + 1];
for (int i = 0; i < coordFactors.Length; i++)
{
coordFactors[i] = disableCoord ? 1.0f : weight.Coord(i, maxCoord);
}
}
public override bool Score(ICollector collector, int max)
{
bool more;
Bucket tmp;
FakeScorer fs = new FakeScorer();
// The internal loop will set the score and doc before calling collect.
collector.SetScorer(fs);
do
{
bucketTable.first = null;
while (current != null) // more queued
{
// check prohibited & required
if ((current.Bits & PROHIBITED_MASK) == 0)
{
// TODO: re-enable this if BQ ever sends us required
// clauses
//&& (current.bits & requiredMask) == requiredMask) {
// NOTE: Lucene always passes max =
// Integer.MAX_VALUE today, because we never embed
// a BooleanScorer inside another (even though
// that should work)... but in theory an outside
// app could pass a different max so we must check
// it:
if (current.Doc >= max)
{
tmp = current;
current = current.Next;
tmp.Next = bucketTable.first;
bucketTable.first = tmp;
continue;
}
if (current.Coord >= minNrShouldMatch)
{
fs.score = (float)(current.Score * coordFactors[current.Coord]);
fs.doc = current.Doc;
fs.freq = current.Coord;
collector.Collect(current.Doc);
}
}
current = current.Next; // pop the queue
}
if (bucketTable.first != null)
{
current = bucketTable.first;
bucketTable.first = current.Next;
return true;
}
// refill the queue
more = false;
end += BucketTable.SIZE;
for (SubScorer sub = scorers; sub != null; sub = sub.Next)
{
if (sub.More)
{
sub.More = sub.Scorer.Score(sub.Collector, end);
more |= sub.More;
}
}
current = bucketTable.first;
} while (current != null || more);
return false;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("boolean(");
for (SubScorer sub = scorers; sub != null; sub = sub.Next)
{
buffer.Append(sub.Scorer.ToString());
buffer.Append(" ");
}
buffer.Append(")");
return buffer.ToString();
}
}
}
| |
/* ====================================================================
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 NPOI.SS.Util
{
using System;
using NPOI.Util;
internal class MutableFPNumber
{
// TODO - what about values between (10<sup>14</sup>-0.5) and (10<sup>14</sup>-0.05) ?
/**
* The minimum value in 'Base-10 normalised form'.<br/>
* When {@link #_binaryExponent} == 46 this is the the minimum {@link #_frac} value
* (10<sup>14</sup>-0.05) * 2^17
* <br/>
* Values between (10<sup>14</sup>-0.05) and 10<sup>14</sup> will be represented as '1'
* followed by 14 zeros.
* Values less than (10<sup>14</sup>-0.05) will get Shifted by one more power of 10
*
* This frac value rounds to '1' followed by fourteen zeros with an incremented decimal exponent
*/
//private static BigInteger BI_MIN_BASE = new BigInteger("0B5E620F47FFFE666", 16);
private static BigInteger BI_MIN_BASE = new BigInteger(new int[] { -1243209484, 2147477094 }, 1);
/**
* For 'Base-10 normalised form'<br/>
* The maximum {@link #_frac} value when {@link #_binaryExponent} == 49
* (10^15-0.5) * 2^14
*/
//private static BigInteger BI_MAX_BASE = new BigInteger("0E35FA9319FFFE000", 16);
private static BigInteger BI_MAX_BASE = new BigInteger(new int[] { -480270031, -1610620928 }, 1);
/**
* Width of a long
*/
private static int C_64 = 64;
/**
* Minimum precision after discarding whole 32-bit words from the significand
*/
private static int MIN_PRECISION = 72;
private BigInteger _significand;
private int _binaryExponent;
public MutableFPNumber(BigInteger frac, int binaryExponent)
{
_significand = frac;
_binaryExponent = binaryExponent;
}
public MutableFPNumber Copy()
{
return new MutableFPNumber(_significand, _binaryExponent);
}
public void Normalise64bit()
{
int oldBitLen = _significand.BitLength();
int sc = oldBitLen - C_64;
if (sc == 0)
{
return;
}
if (sc < 0)
{
throw new InvalidOperationException("Not enough precision");
}
_binaryExponent += sc;
if (sc > 32)
{
int highShift = (sc - 1) & 0xFFFFE0;
_significand = _significand>>(highShift);
sc -= highShift;
oldBitLen -= highShift;
}
if (sc < 1)
{
throw new InvalidOperationException();
}
_significand = Rounder.Round(_significand, sc);
if (_significand.BitLength() > oldBitLen)
{
sc++;
_binaryExponent++;
}
_significand = _significand>>(sc);
}
public int Get64BitNormalisedExponent()
{
//return _binaryExponent + _significand.BitCount() - C_64;
return _binaryExponent + _significand.BitLength() - C_64;
}
public bool IsBelowMaxRep()
{
int sc = _significand.BitLength() - C_64;
//return _significand<(BI_MAX_BASE<<(sc));
return _significand.CompareTo(BI_MAX_BASE.ShiftLeft(sc)) < 0;
}
public bool IsAboveMinRep()
{
int sc = _significand.BitLength() - C_64;
return _significand.CompareTo(BI_MIN_BASE.ShiftLeft(sc)) > 0;
//return _significand>(BI_MIN_BASE<<(sc));
}
public NormalisedDecimal CreateNormalisedDecimal(int pow10)
{
// missingUnderBits is (0..3)
int missingUnderBits = _binaryExponent - 39;
int fracPart = (_significand.IntValue() << missingUnderBits) & 0xFFFF80;
long wholePart = (_significand>>(C_64 - _binaryExponent - 1)).LongValue();
return new NormalisedDecimal(wholePart, fracPart, pow10);
}
public void multiplyByPowerOfTen(int pow10)
{
TenPower tp = TenPower.GetInstance(Math.Abs(pow10));
if (pow10 < 0)
{
mulShift(tp._divisor, tp._divisorShift);
}
else
{
mulShift(tp._multiplicand, tp._multiplierShift);
}
}
private void mulShift(BigInteger multiplicand, int multiplierShift)
{
_significand = _significand*multiplicand;
_binaryExponent += multiplierShift;
// check for too much precision
int sc = (_significand.BitLength() - MIN_PRECISION) & unchecked((int)0xFFFFFFE0);
// mask Makes multiples of 32 which optimises BigInt32.ShiftRight
if (sc > 0)
{
// no need to round because we have at least 8 bits of extra precision
_significand = _significand>>(sc);
_binaryExponent += sc;
}
}
private class Rounder
{
private static BigInteger[] HALF_BITS;
static Rounder()
{
BigInteger[] bis = new BigInteger[33];
long acc = 1;
for (int i = 1; i < bis.Length; i++)
{
bis[i] = new BigInteger(acc);
acc <<= 1;
}
HALF_BITS = bis;
}
/**
* @param nBits number of bits to shift right
*/
public static BigInteger Round(BigInteger bi, int nBits)
{
if (nBits < 1)
{
return bi;
}
return bi+(HALF_BITS[nBits]);
}
}
/**
* Holds values for quick multiplication and division by 10
*/
private class TenPower
{
private static BigInteger FIVE = new BigInteger(5L);// new BigInteger("5",10);
private static TenPower[] _cache = new TenPower[350];
public BigInteger _multiplicand;
public BigInteger _divisor;
public int _divisorShift;
public int _multiplierShift;
private TenPower(int index)
{
//BigInteger fivePowIndex = FIVE.ModPow(new BigInteger(index),FIVE);
BigInteger fivePowIndex = FIVE.Pow(index);
int bitsDueToFiveFactors = fivePowIndex.BitLength();
int px = 80 + bitsDueToFiveFactors;
BigInteger fx = (BigInteger.ONE << px) / (fivePowIndex);
int adj = fx.BitLength() - 80;
_divisor = fx>>(adj);
bitsDueToFiveFactors -= adj;
_divisorShift = -(bitsDueToFiveFactors + index + 80);
int sc = fivePowIndex.BitLength() - 68;
if (sc > 0)
{
_multiplierShift = index + sc;
_multiplicand = fivePowIndex>>(sc);
}
else
{
_multiplierShift = index;
_multiplicand = fivePowIndex;
}
}
public static TenPower GetInstance(int index)
{
TenPower result = _cache[index];
if (result == null)
{
result = new TenPower(index);
_cache[index] = result;
}
return result;
}
}
public ExpandedDouble CreateExpandedDouble()
{
return new ExpandedDouble(_significand, _binaryExponent);
}
}
}
| |
//
// PodSleuthDevice.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using IPod;
using Banshee.Hardware;
namespace Banshee.Dap.Ipod
{
public class PodSleuthDevice : IPod.Device, IVolume
{
internal const string PodsleuthPrefix = "org.podsleuth.ipod.";
private class _ProductionInfo : IPod.ProductionInfo
{
public _ProductionInfo (IVolume volume)
{
SerialNumber = volume.GetPropertyString (PodsleuthPrefix + "serial_number");
FactoryId = volume.GetPropertyString (PodsleuthPrefix + "production.factory_id");
Number = volume.GetPropertyInteger (PodsleuthPrefix + "production.number");
Week = volume.GetPropertyInteger (PodsleuthPrefix + "production.week");
Year = volume.GetPropertyInteger (PodsleuthPrefix + "production.year");
}
}
private class _VolumeInfo : IPod.VolumeInfo
{
private IVolume volume;
public _VolumeInfo (IVolume volume)
{
this.volume = volume;
MountPoint = volume.MountPoint;
Label = volume.GetPropertyString ("volume.label");
IsMountedReadOnly = volume.IsReadOnly;
Uuid = volume.GetPropertyString ("volume.uuid");
}
public override ulong Size {
get { return volume.Capacity; }
}
public override ulong SpaceUsed {
get { return volume.Capacity - (ulong)volume.Available; }
}
}
private class _ModelInfo : IPod.ModelInfo
{
public _ModelInfo (IVolume volume)
{
AdvertisedCapacity = GetVolumeSizeString (volume);
IsUnknown = true;
if (volume.PropertyExists (PodsleuthPrefix + "is_unknown")) {
IsUnknown = volume.GetPropertyBoolean (PodsleuthPrefix + "is_unknown");
}
if (volume.PropertyExists (PodsleuthPrefix + "images.album_art_supported")) {
AlbumArtSupported = volume.GetPropertyBoolean (PodsleuthPrefix + "images.album_art_supported");
}
if (volume.PropertyExists (PodsleuthPrefix + "images.photos_supported")) {
PhotosSupported = volume.GetPropertyBoolean (PodsleuthPrefix + "images.photos_supported");
}
if (volume.PropertyExists (PodsleuthPrefix + "model.device_class")) {
DeviceClass = volume.GetPropertyString (PodsleuthPrefix + "model.device_class");
}
if (volume.PropertyExists (PodsleuthPrefix + "model.generation")) {
Generation = volume.GetPropertyDouble (PodsleuthPrefix + "model.generation");
}
if (volume.PropertyExists (PodsleuthPrefix + "model.shell_color")) {
ShellColor = volume.GetPropertyString (PodsleuthPrefix + "model.shell_color");
}
if (volume.PropertyExists ("info.icon_name")) {
IconName = volume.GetPropertyString ("info.icon_name");
}
if (volume.PropertyExists (PodsleuthPrefix + "capabilities")) {
foreach (string capability in volume.GetPropertyStringList (PodsleuthPrefix + "capabilities")) {
AddCapability (capability);
}
}
}
private static string GetVolumeSizeString (IVolume volume)
{
string format = "GiB";
double value = volume.GetPropertyUInt64 ("volume.size") / 1000.0 / 1000.0 / 1000.0;
if(value < 1.0) {
format = "MiB";
value *= 1000.0;
}
return String.Format ("{0} {1}", (int)Math.Round (value), format);
}
}
private IVolume volume;
private IPod.ProductionInfo production_info;
private IPod.VolumeInfo volume_info;
private IPod.ModelInfo model_info;
public override IPod.ProductionInfo ProductionInfo {
get { return production_info; }
}
public override IPod.VolumeInfo VolumeInfo {
get { return volume_info; }
}
public override IPod.ModelInfo ModelInfo {
get { return model_info; }
}
internal PodSleuthDevice (IVolume volume)
{
this.volume = volume;
volume_info = new _VolumeInfo (volume);
production_info = new _ProductionInfo (volume);
model_info = new _ModelInfo (volume);
if (volume.PropertyExists (PodsleuthPrefix + "control_path")) {
string relative_control = volume.GetPropertyString (PodsleuthPrefix + "control_path");
if (relative_control[0] == Path.DirectorySeparatorChar) {
relative_control = relative_control.Substring (1);
}
ControlPath = Path.Combine(VolumeInfo.MountPoint, relative_control);
}
ArtworkFormats = new ReadOnlyCollection<ArtworkFormat> (LoadArtworkFormats ());
if (volume.PropertyExists (PodsleuthPrefix + "firmware_version")) {
FirmwareVersion = volume.GetPropertyString (PodsleuthPrefix + "firmware_version");
}
if (volume.PropertyExists (PodsleuthPrefix + "firewire_id")) {
FirewireId = volume.GetPropertyString (PodsleuthPrefix + "firewire_id");
}
RescanDisk ();
}
public override void Eject ()
{
volume.Eject ();
}
public override void RescanDisk ()
{
}
private List<ArtworkFormat> LoadArtworkFormats ()
{
List<ArtworkFormat> formats = new List<ArtworkFormat> ();
if (!ModelInfo.AlbumArtSupported) {
return formats;
}
string [] formatList = volume.GetPropertyStringList (PodsleuthPrefix + "images.formats");
foreach (string formatStr in formatList) {
short correlationId, width, height, rotation;
ArtworkUsage usage;
int size;
PixelFormat pformat;
size = 0;
correlationId = width = height = rotation = 0;
usage = ArtworkUsage.Unknown;
pformat = PixelFormat.Unknown;
string[] pairs = formatStr.Split(',');
foreach (string pair in pairs) {
string[] splitPair = pair.Split('=');
if (splitPair.Length != 2) {
continue;
}
string value = splitPair[1];
switch (splitPair[0]) {
case "corr_id": correlationId = Int16.Parse (value); break;
case "width": width = Int16.Parse (value); break;
case "height": height = Int16.Parse (value); break;
case "rotation": rotation = Int16.Parse (value); break;
case "pixel_format":
switch (value) {
case "iyuv": pformat = PixelFormat.IYUV; break;
case "rgb565": pformat = PixelFormat.Rgb565; break;
case "rgb565be": pformat = PixelFormat.Rgb565BE; break;
case "unknown": pformat = PixelFormat.Unknown; break;
}
break;
case "image_type":
switch (value) {
case "photo": usage = ArtworkUsage.Photo; break;
case "album": usage = ArtworkUsage.Cover; break;
/* we don't support this right now
case "chapter": usage = ArtworkUsage.Chapter; break;
*/
}
break;
}
}
if (pformat != PixelFormat.Unknown && usage != ArtworkUsage.Unknown) {
formats.Add (new ArtworkFormat (usage, width, height, correlationId, size, pformat, rotation));
}
}
return formats;
}
#region IVolume Wrapper
string IDevice.Name {
get { return volume.Name; }
}
public void Unmount ()
{
volume.Unmount ();
}
public string Uuid {
get { return volume.Uuid; }
}
public string Serial {
get { return volume.Serial; }
}
public string Product {
get { return volume.Product; }
}
public string Vendor {
get { return volume.Vendor; }
}
public IDeviceMediaCapabilities MediaCapabilities {
get { return volume.MediaCapabilities; }
}
public string DeviceNode {
get { return volume.DeviceNode; }
}
public string MountPoint {
get { return volume.MountPoint; }
}
public bool IsReadOnly {
get { return volume.IsReadOnly; }
}
public ulong Capacity {
get { return volume.Capacity; }
}
public long Available {
get { return volume.Available; }
}
public IBlockDevice Parent {
get { return volume.Parent; }
}
public bool ShouldIgnore {
get { return volume.ShouldIgnore; }
}
public string FileSystem {
get { return volume.FileSystem; }
}
public bool CanEject {
get { return volume.CanEject; }
}
public bool CanUnmount {
get { return volume.CanEject; }
}
public bool PropertyExists (string key)
{
return volume.PropertyExists (key);
}
public string GetPropertyString (string key)
{
return volume.GetPropertyString (key);
}
public double GetPropertyDouble (string key)
{
return volume.GetPropertyDouble (key);
}
public bool GetPropertyBoolean (string key)
{
return volume.GetPropertyBoolean (key);
}
public int GetPropertyInteger (string key)
{
return volume.GetPropertyInteger (key);
}
public ulong GetPropertyUInt64 (string key)
{
return volume.GetPropertyUInt64 (key);
}
public string[] GetPropertyStringList (string key)
{
return volume.GetPropertyStringList (key);
}
public IUsbDevice ResolveRootUsbDevice ()
{
return volume.ResolveRootUsbDevice ();
}
public IUsbPortInfo ResolveUsbPortInfo ()
{
return volume.ResolveUsbPortInfo ();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography {
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Security.Util;
using System.Globalization;
using System.Diagnostics.Contracts;
// We allow only the public components of an RSAParameters object, the Modulus and Exponent
// to be serializable.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct RSAParameters {
public byte[] Exponent;
public byte[] Modulus;
[NonSerialized] public byte[] P;
[NonSerialized] public byte[] Q;
[NonSerialized] public byte[] DP;
[NonSerialized] public byte[] DQ;
[NonSerialized] public byte[] InverseQ;
[NonSerialized] public byte[] D;
}
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class RSA : AsymmetricAlgorithm
{
protected RSA() { }
//
// public methods
//
new static public RSA Create() {
return Create("System.Security.Cryptography.RSA");
}
new static public RSA Create(String algName) {
return (RSA) CryptoConfig.CreateFromName(algName);
}
#if !FEATURE_CORECLR
//
// New RSA encrypt/decrypt/sign/verify RSA abstractions in .NET 4.6+ and .NET Core
//
// Methods that throw DerivedClassMustOverride are effectively abstract but we
// cannot mark them as such as it would be a breaking change. We'll make them
// abstract in .NET Core.
public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) {
throw DerivedClassMustOverride();
}
public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) {
throw DerivedClassMustOverride();
}
public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
throw DerivedClassMustOverride();
}
public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) {
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) {
throw DerivedClassMustOverride();
}
public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
return SignData(data, 0, data.Length, hashAlgorithm, padding);
}
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return SignHash(hash, hashAlgorithm, padding);
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
byte[] hash = HashData(data, hashAlgorithm);
return SignHash(hash, hashAlgorithm, padding);
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifyHash(hash, signature, hashAlgorithm, padding);
}
public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
byte[] hash = HashData(data, hashAlgorithm);
return VerifyHash(hash, signature, hashAlgorithm, padding);
}
private static Exception DerivedClassMustOverride() {
return new NotImplementedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
}
internal static Exception HashAlgorithmNameNullOrEmpty() {
return new ArgumentException(Environment.GetResourceString("Cryptography_HashAlgorithmNameNullOrEmpty"), "hashAlgorithm");
}
#endif
//
// Legacy encrypt/decrypt RSA abstraction from .NET < 4.6
//
// These should be obsolete, but we can't mark them as such here due to rules around not introducing
// source breaks to scenarios that compile against the GAC.
//
// They used to be abstract, but the only concrete implementation in RSACryptoServiceProvider threw
// NotSupportedException! This has been moved up to the base so all subclasses can ignore them moving forward.
// They will also be removed from .NET Core altogether.
//
// The original intent was for these to perform the RSA algorithm without padding/depadding. This can
// be seen by how the RSAXxx(De)Formatter classes call them in the non-RSACryptoServiceProvider case --
// they do the padding/depadding in managed code.
//
// Unfortunately, these formatter classes are still incompatible with RSACng or any derived class that does not
// implement EncryptValue, DecryptValue as the formatters speculatively expected non-RSACryptoServiceProvider
// to do. That needs to be fixed in a subsequent release. We can still do it as it would move an exception to a
// correct result...
//
// [Obsolete]
public virtual byte[] DecryptValue(byte[] rgb) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Method"));
}
// [Obsolete]
public virtual byte[] EncryptValue(byte[] rgb) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Method"));
}
//
// These should also be obsolete (on the base). They aren't well defined nor are they used
// anywhere in the FX apart from checking that they're not null.
//
// For new derived RSA classes, we'll just return "RSA" which is analagous to what ECDsa
// and ECDiffieHellman do.
//
// Note that for compat, RSACryptoServiceProvider still overrides and returns RSA-PKCS1-KEYEX
// and http://www.w3.org/2000/09/xmldsig#rsa-sha1
//
public override string KeyExchangeAlgorithm {
get { return "RSA"; }
}
public override string SignatureAlgorithm {
get { return "RSA"; }
}
// Import/export functions
// We can provide a default implementation of FromXmlString because we require
// every RSA implementation to implement ImportParameters
// All we have to do here is parse the XML.
public override void FromXmlString(String xmlString) {
if (xmlString == null) throw new ArgumentNullException("xmlString");
Contract.EndContractBlock();
RSAParameters rsaParams = new RSAParameters();
Parser p = new Parser(xmlString);
SecurityElement topElement = p.GetTopElement();
// Modulus is always present
String modulusString = topElement.SearchForTextOfLocalName("Modulus");
if (modulusString == null) {
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","RSA","Modulus"));
}
rsaParams.Modulus = Convert.FromBase64String(Utils.DiscardWhiteSpaces(modulusString));
// Exponent is always present
String exponentString = topElement.SearchForTextOfLocalName("Exponent");
if (exponentString == null) {
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","RSA","Exponent"));
}
rsaParams.Exponent = Convert.FromBase64String(Utils.DiscardWhiteSpaces(exponentString));
// P is optional
String pString = topElement.SearchForTextOfLocalName("P");
if (pString != null) rsaParams.P = Convert.FromBase64String(Utils.DiscardWhiteSpaces(pString));
// Q is optional
String qString = topElement.SearchForTextOfLocalName("Q");
if (qString != null) rsaParams.Q = Convert.FromBase64String(Utils.DiscardWhiteSpaces(qString));
// DP is optional
String dpString = topElement.SearchForTextOfLocalName("DP");
if (dpString != null) rsaParams.DP = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dpString));
// DQ is optional
String dqString = topElement.SearchForTextOfLocalName("DQ");
if (dqString != null) rsaParams.DQ = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dqString));
// InverseQ is optional
String inverseQString = topElement.SearchForTextOfLocalName("InverseQ");
if (inverseQString != null) rsaParams.InverseQ = Convert.FromBase64String(Utils.DiscardWhiteSpaces(inverseQString));
// D is optional
String dString = topElement.SearchForTextOfLocalName("D");
if (dString != null) rsaParams.D = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dString));
ImportParameters(rsaParams);
}
// We can provide a default implementation of ToXmlString because we require
// every RSA implementation to implement ImportParameters
// If includePrivateParameters is false, this is just an XMLDSIG RSAKeyValue
// clause. If includePrivateParameters is true, then we extend RSAKeyValue with
// the other (private) elements.
public override String ToXmlString(bool includePrivateParameters) {
// From the XMLDSIG spec, RFC 3075, Section 6.4.2, an RSAKeyValue looks like this:
/*
<element name="RSAKeyValue">
<complexType>
<sequence>
<element name="Modulus" type="ds:CryptoBinary"/>
<element name="Exponent" type="ds:CryptoBinary"/>
</sequence>
</complexType>
</element>
*/
// we extend appropriately for private components
RSAParameters rsaParams = this.ExportParameters(includePrivateParameters);
StringBuilder sb = new StringBuilder();
sb.Append("<RSAKeyValue>");
// Add the modulus
sb.Append("<Modulus>"+Convert.ToBase64String(rsaParams.Modulus)+"</Modulus>");
// Add the exponent
sb.Append("<Exponent>"+Convert.ToBase64String(rsaParams.Exponent)+"</Exponent>");
if (includePrivateParameters) {
// Add the private components
sb.Append("<P>"+Convert.ToBase64String(rsaParams.P)+"</P>");
sb.Append("<Q>"+Convert.ToBase64String(rsaParams.Q)+"</Q>");
sb.Append("<DP>"+Convert.ToBase64String(rsaParams.DP)+"</DP>");
sb.Append("<DQ>"+Convert.ToBase64String(rsaParams.DQ)+"</DQ>");
sb.Append("<InverseQ>"+Convert.ToBase64String(rsaParams.InverseQ)+"</InverseQ>");
sb.Append("<D>"+Convert.ToBase64String(rsaParams.D)+"</D>");
}
sb.Append("</RSAKeyValue>");
return(sb.ToString());
}
abstract public RSAParameters ExportParameters(bool includePrivateParameters);
abstract public void ImportParameters(RSAParameters parameters);
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Spring.Collections;
using Spring.Core.IO;
using Spring.Expressions;
using Spring.Objects;
using Spring.Objects.Factory.Xml;
using Spring.Validation.Actions;
namespace Spring.Validation
{
/// <summary>
/// Unit tests for the CollectionValidator class.
/// </summary>
/// <author>Damjan Tomic</author>
[TestFixture]
public class CollectionValidatorTests
{
[Test]
public void DefaultsToFastValidateIsFalse()
{
CollectionValidator cg = new CollectionValidator();
Assert.IsFalse(cg.FastValidate);
}
[Test]
public void TestCollection()
{
IList persons = new ArrayList();
persons.Add(new TestObject("Damjan Tomic", 24));
persons.Add(new TestObject("Goran Milosavljevic", 24));
persons.Add(new TestObject("Ivan Cikic", 28));
RequiredValidator req = new RequiredValidator("Name", "true");
RegularExpressionValidator reg = new RegularExpressionValidator("Name", "true", @"[a-z]*\s[a-z]*");
reg.Options = RegexOptions.IgnoreCase;
CollectionValidator validator = new CollectionValidator();
validator.Validators.Add(req);
validator.Validators.Add(reg);
Assert.IsTrue(validator.Validate(persons, new ValidationErrors()));
}
[Test]
public void TestDifferentCollectionTypes()
{
const string xml = @"<?xml version='1.0' encoding='UTF-8' ?>
<objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'>
<v:group id='validatePerson' when='T(Spring.Objects.TestObject) == #this.GetType()'>
<v:required id ='req' when='true' test='Name'/>
<v:regex id ='reg' test='Name'>
<v:property name='Expression' value='[a-z]*\s[a-z]*'/>
<v:property name='Options' value='IgnoreCase'/>
<v:message id='reg1' providers='regularni' when='true'>
<v:param value='#this.ToString()'/>
</v:message>
</v:regex>
</v:group>
<v:collection id='collectionValidator' validate-all='true'>
<v:ref name='validatePerson'/>
</v:collection>
</objects>";
MemoryStream stream = new MemoryStream(new UTF8Encoding().GetBytes(xml));
IResource resource = new InputStreamResource(stream, "collectionValidator");
XmlObjectFactory objectFactory = new XmlObjectFactory(resource, null);
CollectionValidator validator = (CollectionValidator) objectFactory.GetObject("collectionValidator");
IList listPersons = new ArrayList();
IDictionary dictPersons = new Hashtable();
ISet setPersons = new ListSet();
listPersons.Add(new TestObject("DAMJAN Tomic", 24));
listPersons.Add(new TestObject("Goran Milosavljevic", 24));
listPersons.Add(new TestObject("Ivan CIKIC", 28));
dictPersons.Add(1, listPersons[0]);
dictPersons.Add(2, listPersons[1]);
dictPersons.Add(3, listPersons[2]);
setPersons.AddAll(listPersons);
IValidationErrors ve = new ValidationErrors();
Assert.IsTrue(validator.Validate(listPersons, ve));
Assert.IsTrue(ve.IsEmpty);
Assert.IsTrue(validator.Validate(dictPersons, ve));
Assert.IsTrue(ve.IsEmpty);
Assert.IsTrue(validator.Validate(setPersons, ve));
Assert.IsTrue(ve.IsEmpty);
}
[Test]
public void TestWithWrongArgumentType()
{
RequiredValidator req = new RequiredValidator("Name", "true");
CollectionValidator validator = new CollectionValidator();
validator.Validators.Add(req);
TestObject tObj = new TestObject("Damjan Tomic", 24);
//This should cause the ArgumentException because tObj is not a Collection
Assert.Throws<ArgumentException>(() => validator.Validate(tObj, new ValidationErrors()));
}
[Test]
public void TestValidationErrorsAreCollected()
{
IList persons = new ArrayList();
persons.Add(new TestObject(null, 24));
persons.Add(new TestObject("Goran Milosavljevic", 24));
persons.Add(new TestObject("Ivan Cikic", 28));
persons.Add(new TestObject(null, 20));
RequiredValidator req = new RequiredValidator("Name", "true");
req.Actions.Add(new ErrorMessageAction("1", new string[] { "firstProvider", "secondProvider" }));
CollectionValidator validator = new CollectionValidator(true,true);
validator.Validators.Add(req);
IValidationErrors ve = new ValidationErrors();
Assert.IsFalse(validator.Validate(persons, ve));
Assert.IsFalse(ve.IsEmpty);
}
[Test]
public void TestWithNull()
{
CollectionValidator validator = new CollectionValidator();
//This should cause the ArgumentException because we passed null into Validate method
Assert.Throws<ArgumentException>(() => validator.Validate(null, new ValidationErrors()));
}
[Test]
public void TestNestingCollectionValidator()
{
Society soc = new Society();
soc.Members.Add(new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"));
soc.Members.Add(new Inventor("Mihajlo Pupin", new DateTime(1854, 10, 9), "Serbian"));
RequiredValidator req = new RequiredValidator("Name", "true");
RegularExpressionValidator reg = new RegularExpressionValidator("Name", "true", @"[a-z]*\s[a-z]*");
reg.Options = RegexOptions.IgnoreCase;
CollectionValidator validator = new CollectionValidator();
validator.Validators.Add(req);
validator.Validators.Add(reg);
validator.Context = Expression.Parse("Members");
Assert.IsTrue(validator.Validate(soc, new ValidationErrors()));
validator.Context = null;
Assert.IsTrue(validator.Validate(soc.Members, new ValidationErrors()));
}
[Test]
public void TestNestingCollectionValidatorWithXMLDescription()
{
const string xml = @"<?xml version='1.0' encoding='UTF-8' ?>
<objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'>
<v:group id='validatePerson' when='T(Spring.Objects.TestObject) == #this.GetType()'>
<v:required id ='req' when='true' test='Name'/>
<v:regex id ='reg' test='Name'>
<v:property name='Expression' value='[a-z]*\s[a-z]*'/>
<v:property name='Options' value='IgnoreCase'/>
<v:message id='reg1' providers='regExpr' when='true'>
<v:param value='#this.ToString()'/>
</v:message>
</v:regex>
</v:group>
<v:group id='validator'>
<v:collection id='collectionValidator' validate-all='true' context='Members' include-element-errors='true'>
<v:message id='coll1' providers='membersCollection' when='true'>
<v:param value='#this.ToString()'/>
</v:message>
<v:ref name='validatePerson'/>
</v:collection>
</v:group>
</objects>";
MemoryStream stream = new MemoryStream(new UTF8Encoding().GetBytes(xml));
IResource resource = new InputStreamResource(stream, "collection validator test");
XmlObjectFactory objectFactory = new XmlObjectFactory(resource, null);
ValidatorGroup validator = (ValidatorGroup) objectFactory.GetObject("validator");
Society soc = new Society();
soc.Members.Add(new TestObject("Damjan Tomic", 24));
soc.Members.Add(new TestObject("Goran Milosavljevic", 24));
soc.Members.Add(new TestObject("Ivan Cikic", 28));
IValidationErrors err1 = new ValidationErrors();
Assert.IsTrue(validator.Validate(soc, err1));
soc.Members.Add(new TestObject("foo", 30));
soc.Members.Add(new TestObject("bar", 30));
Assert.IsFalse(validator.Validate(soc, err1));
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Monitor
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
namespace System.Threading
{
using System;
////using System.Security.Permissions;
////using System.Runtime.Remoting;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
////using System.Runtime.Versioning;
////[HostProtection( Synchronization = true, ExternalThreading = true )]
public static class Monitor
{
/*=========================================================================
** Obtain the monitor lock of obj. Will block if another thread holds the lock
** Will not block if the current thread holds the lock,
** however the caller must ensure that the same number of Exit
** calls are made as there were Enter calls.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
public static extern void Enter( Object obj );
//// // This should be made public in a future version.
//// // Use a ref bool instead of out to ensure that unverifiable code must
//// // initialize this value to something. If we used out, the value
//// // could be uninitialized if we threw an exception in our prolog.
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// internal static extern void ReliableEnter( Object obj, ref bool tookLock );
public static void Enter( Object obj, ref bool lockTaken )
{
if(obj == null)
{
throw new ArgumentNullException();
}
// The input must be false.
if (lockTaken == true)
{
lockTaken = false;
throw new ArgumentException();
}
//The output is true if the lock is acquired; otherwise, the output is
// false. The output is set even if an exception occurs during the attempt
// to acquire the lock.
Enter(obj);
lockTaken = true;
}
/*=========================================================================
** Release the monitor lock. If one or more threads are waiting to acquire the
** lock, and the current thread has executed as many Exits as
** Enters, one of the threads will be unblocked and allowed to proceed.
**
** Exceptions: ArgumentNullException if object is null.
** SynchronizationLockException if the current thread does not
** own the lock.
=========================================================================*/
//// [ResourceExposure( ResourceScope.None )]
//// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[MethodImpl( MethodImplOptions.InternalCall )]
public static extern void Exit( Object obj );
/*=========================================================================
** Similar to Enter, but will never block. That is, if the current thread can
** acquire the monitor lock without blocking, it will do so and TRUE will
** be returned. Otherwise FALSE will be returned.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
public static bool TryEnter( Object obj )
{
return TryEnterTimeout( obj, 0 );
}
/*=========================================================================
** Version of TryEnter that will block, but only up to a timeout period
** expressed in milliseconds. If timeout == Timeout.Infinite the method
** becomes equivalent to Enter.
**
** Exceptions: ArgumentNullException if object is null.
** ArgumentException if timeout < 0.
=========================================================================*/
public static bool TryEnter( Object obj, int millisecondsTimeout )
{
return TryEnterTimeout( obj, millisecondsTimeout );
}
public static bool TryEnter( Object obj, TimeSpan timeout )
{
long tm = (long)timeout.TotalMilliseconds;
if(tm < -1 || tm > (long)Int32.MaxValue)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
return TryEnterTimeout( obj, (int)tm );
}
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern bool TryEnterTimeout( Object obj, int timeout );
/*========================================================================
** Waits for notification from the object (via a Pulse/PulseAll).
** timeout indicates how long to wait before the method returns.
** This method acquires the monitor waithandle for the object
** If this thread holds the monitor lock for the object, it releases it.
** On exit from the method, it obtains the monitor lock back.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern bool ObjWait( bool exitContext, int millisecondsTimeout, Object obj );
public static bool Wait( Object obj, int millisecondsTimeout, bool exitContext )
{
if(obj == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "obj" );
#else
throw new ArgumentNullException();
#endif
}
return ObjWait( exitContext, millisecondsTimeout, obj );
}
public static bool Wait( Object obj, TimeSpan timeout, bool exitContext )
{
long tm = (long)timeout.TotalMilliseconds;
if(tm < -1 || tm > (long)Int32.MaxValue)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
return Wait( obj, (int)tm, exitContext );
}
public static bool Wait( Object obj, int millisecondsTimeout )
{
return Wait( obj, millisecondsTimeout, false );
}
public static bool Wait( Object obj, TimeSpan timeout )
{
long tm = (long)timeout.TotalMilliseconds;
if(tm < -1 || tm > (long)Int32.MaxValue)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
return Wait( obj, (int)tm, false );
}
public static bool Wait( Object obj )
{
return Wait( obj, Timeout.Infinite, false );
}
/*========================================================================
** Sends a notification to a single waiting object.
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern void ObjPulse( Object obj );
public static void Pulse( Object obj )
{
if(obj == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "obj" );
#else
throw new ArgumentNullException();
#endif
}
ObjPulse( obj );
}
/*========================================================================
** Sends a notification to all waiting objects.
========================================================================*/
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern void ObjPulseAll( Object obj );
public static void PulseAll( Object obj )
{
if(obj == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "obj" );
#else
throw new ArgumentNullException();
#endif
}
ObjPulseAll( obj );
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.Win32;
using System.Threading;
using System.IO;
namespace Earlab
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private RegistryKey mKey;
private RegistryString mModuleDirectory;
private RegistryString mOutputDirectory;
private RegistryString mDiagramFile;
private RegistryString mParameterFile;
private RegistryInt mFrameCount;
private RegistryFormWindowState mWindowState;
private RegistryPoint mWindowLocation;
private RegistrySize mWindowSize;
private Thread mExecutionThread;
private bool mStopModel, mRunning, mStoppedCleanly;
private LogCallback mLogCallback;
private static Form1 mMainForm;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuFileExit;
private System.Windows.Forms.MenuItem menuModelChooseDiagramFile;
private System.Windows.Forms.MenuItem menuModelChooseParameterFile;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.MenuItem menuModelRun;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuEnvironmentSetModuleDirectory;
private System.Windows.Forms.MenuItem menuEnvironmentSetOutputDirectory;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.TextBox txtStatusDisplay;
private System.Windows.Forms.NumericUpDown udFrameCount;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.StatusBarPanel sbTextPanel;
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.RichTextBox logDisplay;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.Button btnAbort;
private System.Windows.Forms.FolderBrowserDialog folderBrowser;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.MenuItem menuHelp;
private System.Windows.Forms.MenuItem menuHelpAbout;
private System.ComponentModel.IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
mLogCallback = new LogCallback(LogCallback);
mKey = Registry.CurrentUser.CreateSubKey(@"Software\Earlab\DesktopEarlabGUI");
mModuleDirectory = new RegistryString(mKey, "ModuleDirectory", null);
mOutputDirectory = new RegistryString(mKey, "OutputDirectory", null);
mDiagramFile = new RegistryString(mKey, "RunParameterFile", null);
mParameterFile = new RegistryString(mKey, "ModuleParameterFile", null);
mFrameCount = new RegistryInt(mKey, "FrameCount", 0);
udFrameCount.Value = mFrameCount.Value;
mWindowState = new RegistryFormWindowState(mKey, "WindowState", FormWindowState.Normal);
mWindowLocation = new RegistryPoint(mKey, "WindowLocation", this.Location);
mWindowSize = new RegistrySize(mKey, "WindowSize", this.MinimumSize);
this.Location = mWindowLocation.Value;
this.Size = mWindowSize.Value;
this.WindowState = mWindowState.Value;
udFrameCount.Focus();
UpdateStatusDisplay();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuFileExit = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.menuModelChooseDiagramFile = new System.Windows.Forms.MenuItem();
this.menuModelChooseParameterFile = new System.Windows.Forms.MenuItem();
this.menuModelRun = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuEnvironmentSetModuleDirectory = new System.Windows.Forms.MenuItem();
this.menuEnvironmentSetOutputDirectory = new System.Windows.Forms.MenuItem();
this.label3 = new System.Windows.Forms.Label();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.txtStatusDisplay = new System.Windows.Forms.TextBox();
this.udFrameCount = new System.Windows.Forms.NumericUpDown();
this.statusBar = new System.Windows.Forms.StatusBar();
this.sbTextPanel = new System.Windows.Forms.StatusBarPanel();
this.btnRun = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.logDisplay = new System.Windows.Forms.RichTextBox();
this.timer = new System.Windows.Forms.Timer(this.components);
this.btnAbort = new System.Windows.Forms.Button();
this.folderBrowser = new System.Windows.Forms.FolderBrowserDialog();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.menuHelp = new System.Windows.Forms.MenuItem();
this.menuHelpAbout = new System.Windows.Forms.MenuItem();
((System.ComponentModel.ISupportInitialize)(this.udFrameCount)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.sbTextPanel)).BeginInit();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem6,
this.menuItem2,
this.menuHelp});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuFileExit});
this.menuItem1.Text = "&File";
//
// menuFileExit
//
this.menuFileExit.Index = 0;
this.menuFileExit.Shortcut = System.Windows.Forms.Shortcut.AltF4;
this.menuFileExit.Text = "E&xit";
this.menuFileExit.Click += new System.EventHandler(this.menuFileExit_Click);
//
// menuItem6
//
this.menuItem6.Index = 1;
this.menuItem6.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuModelChooseDiagramFile,
this.menuModelChooseParameterFile,
this.menuModelRun});
this.menuItem6.Text = "&Model";
//
// menuModelChooseDiagramFile
//
this.menuModelChooseDiagramFile.Index = 0;
this.menuModelChooseDiagramFile.Shortcut = System.Windows.Forms.Shortcut.CtrlD;
this.menuModelChooseDiagramFile.Text = "Choose Diagram File...";
this.menuModelChooseDiagramFile.Click += new System.EventHandler(this.menuModelChooseDiagramFile_Click);
//
// menuModelChooseParameterFile
//
this.menuModelChooseParameterFile.Index = 1;
this.menuModelChooseParameterFile.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
this.menuModelChooseParameterFile.Text = "Choose Parameter File...";
this.menuModelChooseParameterFile.Click += new System.EventHandler(this.menuModelChooseParameterFile_Click);
//
// menuModelRun
//
this.menuModelRun.Index = 2;
this.menuModelRun.Shortcut = System.Windows.Forms.Shortcut.F5;
this.menuModelRun.Text = "Run Model...";
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuEnvironmentSetModuleDirectory,
this.menuEnvironmentSetOutputDirectory});
this.menuItem2.Text = "Environment";
//
// menuEnvironmentSetModuleDirectory
//
this.menuEnvironmentSetModuleDirectory.Index = 0;
this.menuEnvironmentSetModuleDirectory.Text = "Set Module Directory...";
this.menuEnvironmentSetModuleDirectory.Click += new System.EventHandler(this.menuEnvironmentSetModuleDirectory_Click);
//
// menuEnvironmentSetOutputDirectory
//
this.menuEnvironmentSetOutputDirectory.Index = 1;
this.menuEnvironmentSetOutputDirectory.Text = "Set Output Directory...";
this.menuEnvironmentSetOutputDirectory.Click += new System.EventHandler(this.menuEnvironmentSetOutputDirectory_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(8, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(68, 16);
this.label3.TabIndex = 7;
this.label3.Text = "Frame count";
//
// txtStatusDisplay
//
this.txtStatusDisplay.AcceptsReturn = true;
this.txtStatusDisplay.AcceptsTab = true;
this.txtStatusDisplay.BackColor = System.Drawing.SystemColors.Control;
this.txtStatusDisplay.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtStatusDisplay.Location = new System.Drawing.Point(8, 8);
this.txtStatusDisplay.Multiline = true;
this.txtStatusDisplay.Name = "txtStatusDisplay";
this.txtStatusDisplay.ReadOnly = true;
this.txtStatusDisplay.Size = new System.Drawing.Size(536, 72);
this.txtStatusDisplay.TabIndex = 14;
this.txtStatusDisplay.TabStop = false;
this.txtStatusDisplay.Text = "Status Display";
//
// udFrameCount
//
this.udFrameCount.Location = new System.Drawing.Point(8, 104);
this.udFrameCount.Maximum = new System.Decimal(new int[] {
1000000,
0,
0,
0});
this.udFrameCount.Name = "udFrameCount";
this.udFrameCount.Size = new System.Drawing.Size(72, 20);
this.udFrameCount.TabIndex = 1;
this.udFrameCount.ValueChanged += new System.EventHandler(this.udFrameCount_ValueChanged);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 325);
this.statusBar.Name = "statusBar";
this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.sbTextPanel});
this.statusBar.ShowPanels = true;
this.statusBar.Size = new System.Drawing.Size(552, 22);
this.statusBar.TabIndex = 16;
//
// sbTextPanel
//
this.sbTextPanel.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
this.sbTextPanel.Text = "Not Ready";
this.sbTextPanel.Width = 200;
//
// btnRun
//
this.btnRun.Enabled = false;
this.btnRun.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnRun.Location = new System.Drawing.Point(104, 104);
this.btnRun.Name = "btnRun";
this.btnRun.TabIndex = 2;
this.btnRun.Text = "Run";
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnStop
//
this.btnStop.Enabled = false;
this.btnStop.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnStop.Location = new System.Drawing.Point(192, 104);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 3;
this.btnStop.Text = "Stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// logDisplay
//
this.logDisplay.AcceptsTab = true;
this.logDisplay.Location = new System.Drawing.Point(8, 128);
this.logDisplay.Name = "logDisplay";
this.logDisplay.ReadOnly = true;
this.logDisplay.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.logDisplay.Size = new System.Drawing.Size(536, 168);
this.logDisplay.TabIndex = 19;
this.logDisplay.TabStop = false;
this.logDisplay.Text = "";
this.logDisplay.TextChanged += new System.EventHandler(this.logDisplay_TextChanged);
//
// timer
//
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// btnAbort
//
this.btnAbort.Enabled = false;
this.btnAbort.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnAbort.Location = new System.Drawing.Point(280, 104);
this.btnAbort.Name = "btnAbort";
this.btnAbort.TabIndex = 20;
this.btnAbort.Text = "Abort";
this.btnAbort.Click += new System.EventHandler(this.btnAbort_Click);
//
// progressBar
//
this.progressBar.Location = new System.Drawing.Point(204, 320);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(328, 16);
this.progressBar.TabIndex = 21;
//
// menuHelp
//
this.menuHelp.Index = 3;
this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuHelpAbout});
this.menuHelp.Text = "Help";
//
// menuHelpAbout
//
this.menuHelpAbout.Index = 0;
this.menuHelpAbout.Text = "About Desktop Earlab...";
this.menuHelpAbout.Click += new System.EventHandler(this.menuHelpAbout_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(552, 347);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.btnAbort);
this.Controls.Add(this.logDisplay);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnRun);
this.Controls.Add(this.udFrameCount);
this.Controls.Add(this.txtStatusDisplay);
this.Controls.Add(this.label3);
this.Controls.Add(this.statusBar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.MinimumSize = new System.Drawing.Size(448, 381);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Desktop Earlab";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.LocationChanged += new System.EventHandler(this.Form1_LocationChanged);
((System.ComponentModel.ISupportInitialize)(this.udFrameCount)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.sbTextPanel)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
mMainForm = new Form1();
Application.Run(mMainForm);
}
static void LogCallback(String Message)
{
mMainForm.Log(Message);
}
private void menuEnvironmentSetModuleDirectory_Click(object sender, System.EventArgs e)
{
folderBrowser.Reset();
//folderBrowser.RootFolder = Environment.SpecialFolder.Desktop;
if (mModuleDirectory != null)
folderBrowser.SelectedPath = mModuleDirectory.Value;
folderBrowser.ShowNewFolderButton = false;
folderBrowser.Description = "Choose the directory that contains the Earlab modules";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
mModuleDirectory.Value = folderBrowser.SelectedPath;
UpdateStatusDisplay();
}
}
private void menuEnvironmentSetOutputDirectory_Click(object sender, System.EventArgs e)
{
folderBrowser.Reset();
if (mModuleDirectory != null)
folderBrowser.SelectedPath = mOutputDirectory.Value;
folderBrowser.ShowNewFolderButton = true;
folderBrowser.Description = "Choose the directory that will hold your output files";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
mOutputDirectory.Value = folderBrowser.SelectedPath;
UpdateStatusDisplay();
}
}
private void menuFileExit_Click(object sender, System.EventArgs e)
{
StopModelAndWait();
Application.Exit();
}
private void menuModelChooseDiagramFile_Click(object sender, System.EventArgs e)
{
openFileDialog.FileName = mDiagramFile.Value;
openFileDialog.Title = "Choose Diagram file";
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Filter = "Diagram files (*.diagram)|*.diagram|All files (*.*)|*.*";
openFileDialog.FilterIndex = 0;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.ValidateNames = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
mDiagramFile.Value = openFileDialog.FileName;
UpdateStatusDisplay();
}
}
private void menuModelChooseParameterFile_Click(object sender, System.EventArgs e)
{
openFileDialog.FileName = mParameterFile.Value;
openFileDialog.Title = "Choose Parameter file";
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Filter = "Parameter files (*.parameters)|*.parameters|All files (*.*)|*.*";
openFileDialog.FilterIndex = 0;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.ValidateNames = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
mParameterFile.Value = openFileDialog.FileName;
UpdateStatusDisplay();
}
}
private void UpdateStatusDisplay()
{
string [] MyLines = new string[5];
bool SimOK = true;
int LineCount = 0;
if (mDiagramFile.Value != null)
MyLines[LineCount++] = "Diagram file is \"" + mDiagramFile.Value + "\"";
else
{
MyLines[LineCount++] = "Diagram file is not set";
SimOK = false;
}
if (mParameterFile.Value != null)
MyLines[LineCount++] = "Parameter file is \"" + mParameterFile.Value + "\"";
else
{
MyLines[LineCount++] = "Parameter file is not set";
SimOK = false;
}
if (mOutputDirectory.Value != null)
MyLines[LineCount++] = "Output Directory is \"" + mOutputDirectory.Value + "\"";
else
{
MyLines[LineCount++] = "Output Directory is not set";
SimOK = false;
}
if (mModuleDirectory.Value != null)
MyLines[LineCount++] = "Module Directory is \"" + mModuleDirectory.Value + "\"";
else
{
MyLines[LineCount++] = "Module Directory is not set";
SimOK = false;
}
if (mFrameCount.Value != 0)
MyLines[LineCount++] = "Simulation will run for " + mFrameCount.Value + " frames";
else
{
MyLines[LineCount++] = "Frame count not set";
SimOK = false;
}
txtStatusDisplay.Lines = MyLines;
if (SimOK)
{
sbTextPanel.Text = "Ready";
btnRun.Enabled = true;
txtStatusDisplay.ForeColor = SystemColors.ControlText;
}
else
{
btnRun.Enabled = false;
sbTextPanel.Text = "Not Ready";
txtStatusDisplay.ForeColor = Color.Red;
}
txtStatusDisplay.SelectionLength = 0;
udFrameCount.Focus();
}
private void udFrameCount_ValueChanged(object sender, System.EventArgs e)
{
mFrameCount.Value = (int)udFrameCount.Value;
UpdateStatusDisplay();
}
private void btnRun_Click(object sender, System.EventArgs e)
{
mExecutionThread = new Thread(new ThreadStart(RunModel));
mExecutionThread.IsBackground = true;
mExecutionThread.Name = "Model Execution Thread";
mStopModel = false;
progressBar.Value = 0;
progressBar.Visible = true;
progressBar.Minimum = 0;
progressBar.Maximum = mFrameCount.Value + 1;
mExecutionThread.Priority = ThreadPriority.BelowNormal;
mExecutionThread.Start();
timer.Enabled = true;
}
private void btnStop_Click(object sender, System.EventArgs e)
{
btnAbort.Enabled = true;
StopModel();
}
private void RunModel()
{
int i;
DesktopEarlabDLL theDLL = new DesktopEarlabDLL();
mStoppedCleanly = false;
btnRun.Enabled = false;
btnStop.Enabled = true;
udFrameCount.Enabled = false;
progressBar.Visible = true;
ClearLog();
mRunning = false;
sbTextPanel.Text = "Running";
Log("Starting simulation");
theDLL.SetLogCallback(mLogCallback);
Log("Module directory: \"" + mModuleDirectory.Value + "\"");
if (theDLL.SetModuleDirectory(mModuleDirectory.Value) == 0)
{
Log("Error setting module directory");
return;
}
Log("Model configuration: \"" + mDiagramFile.Value + "\"");
if (theDLL.LoadModelConfigFile(mDiagramFile.Value, 1000.0f) == 0)
{
Log("Error loading model config file");
return;
}
Log("Module parameters: \"" + mParameterFile.Value + "\"");
if (theDLL.LoadModuleParameters(mParameterFile.Value) == 0)
{
Log("Error loading module parameter file");
return;
}
Log("Setting current directory to output directory (\"" + mOutputDirectory.Value + "\")");
theDLL.SetOutputDirectory(mOutputDirectory.Value);
Log("Starting modules");
if (theDLL.StartModules() == 0)
{
Log("Error starting modules");
return;
}
for (i = 0; i < mFrameCount.Value; i++)
{
mRunning = true;
if (mStopModel)
break;
progressBar.Value = i;
sbTextPanel.Text = "Processing frame " + (i + 1) + " of " + mFrameCount.Value;
Log("Starting frame " + (i + 1) + " of " + mFrameCount.Value);
try
{
if (theDLL.AdvanceModules() == 0)
{
Log("Error processing frame " + i + " of " + mFrameCount.Value);
return;
}
}
catch (Exception e)
{
Log("Caught exception: " + e.ToString());
}
Application.DoEvents();
Thread.Sleep(100);
}
sbTextPanel.Text = "Stopping";
Log("Stopping modules");
if (theDLL.StopModules() == 0)
{
Log("Error stopping modules");
return;
}
Log("Unloading modules");
if (theDLL.UnloadModel() == 0)
{
Log("Error unloading model");
return;
}
btnRun.Enabled = true;
btnStop.Enabled = false;
btnAbort.Enabled = false;
udFrameCount.Enabled = true;
progressBar.Visible = false;
UpdateStatusDisplay();
udFrameCount.Focus();
mStoppedCleanly = true;
mRunning = false;
}
void ClearLog()
{
logDisplay.Text = "";
}
void Log(string Message)
{
logDisplay.AppendText(DateTime.Now.ToString() + " " + Message + "\r\n");
}
private void logDisplay_TextChanged(object sender, System.EventArgs e)
{
logDisplay.Focus();
logDisplay.SelectionStart = logDisplay.TextLength;
//logDisplay.SelectionLength = 0;
logDisplay.ScrollToCaret();
}
private void Form1_Resize(object sender, System.EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
mWindowSize.Value = this.Size;
txtStatusDisplay.Width = this.ClientSize.Width - 16;
logDisplay.Width = this.ClientSize.Width - 16;
logDisplay.Height = (this.ClientSize.Height - 24) - logDisplay.Top;
progressBar.Top = statusBar.Top + ((statusBar.Height - progressBar.Height) / 2);
progressBar.Width = this.Width - progressBar.Left - 30;
}
mWindowState.Value = this.WindowState;
}
private void Form1_LocationChanged(object sender, System.EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
mWindowLocation.Value = this.Location;
mWindowState.Value = this.WindowState;
}
private void StopModel()
{
sbTextPanel.Text = "Stopping (User request)";
Log("User requested stop");
if ((mExecutionThread != null) && mExecutionThread.IsAlive && mRunning)
mStopModel = true;
} // private void StopModel()
private void StopModelAndWait()
{
int WaitTimeout = 3000; // Wait 30 seconds for model to stop
StopModel();
while ((mExecutionThread != null) && mExecutionThread.IsAlive && mRunning && (WaitTimeout > 0))
{
Thread.Sleep(10);
Application.DoEvents();
WaitTimeout--;
}
if (WaitTimeout <= 0)
AbortModel();
} // private void StopModel()
private void AbortModel()
{
if (mExecutionThread.IsAlive)
{
Log("User requested abort");
mExecutionThread.Abort();
mStoppedCleanly = false;
sbTextPanel.Text = "Aborted";
} // if (mExecutionThread.IsAlive)
btnAbort.Enabled = false;
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
StopModelAndWait();
}
private void timer_Tick(object sender, System.EventArgs e)
{
if (!mExecutionThread.IsAlive)
{
if (!mStoppedCleanly)
Log("Model failed");
else
Log("Model stopped");
timer.Enabled = false;
btnRun.Enabled = true;
btnStop.Enabled = false;
btnAbort.Enabled = false;
UpdateStatusDisplay();
progressBar.Visible = false;
progressBar.Value = 0;
}
}
private void btnAbort_Click(object sender, System.EventArgs e)
{
AbortModel();
}
private void Form1_Load(object sender, System.EventArgs e)
{
progressBar.Visible = false;
}
private void menuHelpAbout_Click(object sender, System.EventArgs e)
{
Form About = new EarlabGUI.About();
About.Show();
}
}
}
| |
// <copyright file="PlayGamesHelperObject.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.OurUtils
{
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class PlayGamesHelperObject : MonoBehaviour
{
// our (singleton) instance
private static PlayGamesHelperObject instance = null;
// are we a dummy instance (used in the editor?)
private static bool sIsDummy = false;
// queue of actions to run on the game thread
private static List<System.Action> sQueue = new List<Action>();
// flag that alerts us that we should check the queue
// (we do this just so we don't have to lock() the queue every
// frame to check if it's empty or not).
private volatile static bool sQueueEmpty = true;
// callback for application pause and focus events
private static List<Action<bool>> sPauseCallbackList =
new List<Action<bool>>();
private static List<Action<bool>> sFocusCallbackList =
new List<Action<bool>>();
// Call this once from the game thread
public static void CreateObject()
{
if (instance != null)
{
return;
}
if (Application.isPlaying)
{
// add an invisible game object to the scene
GameObject obj = new GameObject("PlayGames_QueueRunner");
DontDestroyOnLoad(obj);
instance = obj.AddComponent<PlayGamesHelperObject>();
}
else
{
instance = new PlayGamesHelperObject();
sIsDummy = true;
}
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
public void OnDisable()
{
if (instance == this)
{
instance = null;
}
}
public static void RunCoroutine(IEnumerator action)
{
if (instance != null)
{
instance.StartCoroutine(action);
}
}
public static void RunOnGameThread(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (sIsDummy)
{
return;
}
lock (sQueue)
{
sQueue.Add(action);
sQueueEmpty = false;
}
}
public void Update()
{
if (sIsDummy || sQueueEmpty)
{
return;
}
// first copy the shared queue into a local queue
List<System.Action> q = new List<System.Action>();
lock (sQueue)
{
// transfer the whole queue to our local queue
q.AddRange(sQueue);
sQueue.Clear();
sQueueEmpty = true;
}
// execute queued actions (from local queue)
q.ForEach(a => a.Invoke());
}
public void OnApplicationFocus(bool focused)
{
foreach (Action<bool> cb in sFocusCallbackList)
{
try
{
cb(focused);
}
catch (Exception e)
{
Debug.LogError("Exception in OnApplicationFocus:" +
e.Message + "\n" + e.StackTrace);
}
}
}
public void OnApplicationPause(bool paused)
{
foreach (Action<bool> cb in sPauseCallbackList)
{
try
{
cb(paused);
}
catch (Exception e)
{
Debug.LogError("Exception in OnApplicationPause:" +
e.Message + "\n" + e.StackTrace);
}
}
}
/// <summary>
/// Adds a callback that is called when the Unity method OnApplicationFocus
/// is called.
/// </summary>
/// <see cref="OnApplicationFocus"/>
/// <param name="callback">Callback.</param>
public static void AddFocusCallback(Action<bool> callback)
{
if (!sFocusCallbackList.Contains(callback))
{
sFocusCallbackList.Add(callback);
}
}
/// <summary>
/// Removes the callback from the list to call when handling OnApplicationFocus
/// is called.
/// </summary>
/// <returns><c>true</c>, if focus callback was removed, <c>false</c> otherwise.</returns>
/// <param name="callback">Callback.</param>
public static bool RemoveFocusCallback(Action<bool> callback)
{
return sFocusCallbackList.Remove(callback);
}
/// <summary>
/// Adds a callback that is called when the Unity method OnApplicationPause
/// is called.
/// </summary>
/// <see cref="OnApplicationPause"/>
/// <param name="callback">Callback.</param>
public static void AddPauseCallback(Action<bool> callback)
{
if (!sPauseCallbackList.Contains(callback))
{
sPauseCallbackList.Add(callback);
}
}
/// <summary>
/// Removes the callback from the list to call when handling OnApplicationPause
/// is called.
/// </summary>
/// <returns><c>true</c>, if focus callback was removed, <c>false</c> otherwise.</returns>
/// <param name="callback">Callback.</param>
public static bool RemovePauseCallback(Action<bool> callback)
{
return sPauseCallbackList.Remove(callback);
}
}
}
| |
// 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.
// ReSharper disable CheckNamespace
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
namespace System.Linq
// ReSharper restore CheckNamespace
{
/// <summary>
/// LINQ extension method overrides that offer greater efficiency for <see cref="ImmutableArray{T}"/> than the standard LINQ methods
/// </summary>
public static class ImmutableArrayExtensions
{
#region ImmutableArray<T> extensions
/// <summary>
/// Projects each element of a sequence into a new form.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <typeparam name="TResult">The type of the result element.</typeparam>
/// <param name="immutableArray">The immutable array.</param>
/// <param name="selector">The selector.</param>
[Pure]
public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector)
{
immutableArray.ThrowNullRefIfNotInitialized();
// LINQ Select/Where have optimized treatment for arrays.
// They also do not modify the source arrays or expose them to modifications.
// Therefore we will just apply Select/Where to the underlying this.array array.
return immutableArray.array.Select(selector);
}
/// <summary>
/// Projects each element of a sequence to an <see cref="IEnumerable{T}"/>,
/// flattens the resulting sequences into one sequence, and invokes a result
/// selector function on each element therein.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="immutableArray"/>.</typeparam>
/// <typeparam name="TCollection">The type of the intermediate elements collected by <paramref name="collectionSelector"/>.</typeparam>
/// <typeparam name="TResult">The type of the elements of the resulting sequence.</typeparam>
/// <param name="immutableArray">The immutable array.</param>
/// <param name="collectionSelector">A transform function to apply to each element of the input sequence.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> whose elements are the result
/// of invoking the one-to-many transform function <paramref name="collectionSelector"/> on each
/// element of <paramref name="immutableArray"/> and then mapping each of those sequence elements and their
/// corresponding source element to a result element.
/// </returns>
[Pure]
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
this ImmutableArray<TSource> immutableArray,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
immutableArray.ThrowNullRefIfNotInitialized();
if (collectionSelector == null || resultSelector == null)
{
// throw the same exception as would LINQ
return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector);
}
// This SelectMany overload is used by the C# compiler for a query of the form:
// from i in immutableArray
// from j in anotherCollection
// select Something(i, j);
// SelectMany accepts an IEnumerable<TSource>, and ImmutableArray<TSource> is a struct.
// By having a special implementation of SelectMany that operates on the ImmutableArray's
// underlying array, we can avoid a few allocations, in particular for the boxed
// immutable array object that would be allocated when it's passed as an IEnumerable<T>,
// and for the EnumeratorObject that would be allocated when enumerating the boxed array.
return immutableArray.Length == 0 ?
Enumerable.Empty<TResult>() :
SelectManyIterator(immutableArray, collectionSelector, resultSelector);
}
/// <summary>
/// Filters a sequence of values based on a predicate.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
// LINQ Select/Where have optimized treatment for arrays.
// They also do not modify the source arrays or expose them to modifications.
// Therefore we will just apply Select/Where to the underlying this.array array.
return immutableArray.array.Where(predicate);
}
/// <summary>
/// Gets a value indicating whether any elements are in this collection.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static bool Any<T>(this ImmutableArray<T> immutableArray)
{
return immutableArray.Length > 0;
}
/// <summary>
/// Gets a value indicating whether any elements are in this collection
/// that match a given condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="predicate">The predicate.</param>
[Pure]
public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets a value indicating whether all elements in this collection
/// match a given condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// <c>true</c> if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, <c>false</c>.
/// </returns>
[Pure]
public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (!predicate(v))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase
{
immutableArray.ThrowNullRefIfNotInitialized();
items.ThrowNullRefIfNotInitialized();
if (object.ReferenceEquals(immutableArray.array, items.array))
{
return true;
}
if (immutableArray.Length != items.Length)
{
return false;
}
if (comparer == null)
{
comparer = EqualityComparer<TBase>.Default;
}
for (int i = 0; i < immutableArray.Length; i++)
{
if (!comparer.Equals(immutableArray.array[i], items.array[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase
{
Requires.NotNull(items, "items");
if (comparer == null)
{
comparer = EqualityComparer<TBase>.Default;
}
int i = 0;
int n = immutableArray.Length;
foreach (var item in items)
{
if (i == n)
{
return false;
}
if (!comparer.Equals(immutableArray[i], item))
{
return false;
}
i++;
}
return i == n;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase
{
Requires.NotNull(predicate, "predicate");
immutableArray.ThrowNullRefIfNotInitialized();
items.ThrowNullRefIfNotInitialized();
if (object.ReferenceEquals(immutableArray.array, items.array))
{
return true;
}
if (immutableArray.Length != items.Length)
{
return false;
}
for (int i = 0, n = immutableArray.Length; i < n; i++)
{
if (!predicate(immutableArray[i], items[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func)
{
Requires.NotNull(func, "func");
if (immutableArray.Length == 0)
{
return default(T);
}
var result = immutableArray[0];
for (int i = 1, n = immutableArray.Length; i < n; i++)
{
result = func(result, immutableArray[i]);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func)
{
Requires.NotNull(func, "func");
var result = seed;
foreach (var v in immutableArray.array)
{
result = func(result, v);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam>
/// <typeparam name="TResult">The type of result returned by the result selector.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
Requires.NotNull(resultSelector, "resultSelector");
return resultSelector(Aggregate(immutableArray, seed, func));
}
/// <summary>
/// Returns the element at a specified index in a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index)
{
return immutableArray[index];
}
/// <summary>
/// Returns the element at a specified index in a sequence or a default value if the index is out of range.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index)
{
if (index < 0 || index >= immutableArray.Length)
{
return default(T);
}
return immutableArray[index];
}
/// <summary>
/// Returns the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return v;
}
}
// Throw the same exception that LINQ would.
return Enumerable.Empty<T>().First();
}
/// <summary>
/// Returns the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T First<T>(this ImmutableArray<T> immutableArray)
{
// In the event of an empty array, generate the same exception
// that the linq extension method would.
return immutableArray.Length > 0
? immutableArray[0]
: Enumerable.First(immutableArray.array);
}
/// <summary>
/// Returns the first element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray)
{
return immutableArray.array.Length > 0 ? immutableArray.array[0] : default(T);
}
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return v;
}
}
return default(T);
}
/// <summary>
/// Returns the last element of a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T Last<T>(this ImmutableArray<T> immutableArray)
{
// In the event of an empty array, generate the same exception
// that the linq extension method would.
return immutableArray.Length > 0
? immutableArray[immutableArray.Length - 1]
: Enumerable.Last(immutableArray.array);
}
/// <summary>
/// Returns the last element of a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
for (int i = immutableArray.Length - 1; i >= 0; i--)
{
if (predicate(immutableArray[i]))
{
return immutableArray[i];
}
}
// Throw the same exception that LINQ would.
return Enumerable.Empty<T>().Last();
}
/// <summary>
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.LastOrDefault();
}
/// <summary>
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
for (int i = immutableArray.Length - 1; i >= 0; i--)
{
if (predicate(immutableArray[i]))
{
return immutableArray[i];
}
}
return default(T);
}
/// <summary>
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T Single<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.Single();
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
var first = true;
var result = default(T);
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
if (!first)
{
ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would
}
first = false;
result = v;
}
}
if (first)
{
Enumerable.Empty<T>().Single(); // throw the same exception as LINQ would
}
return result;
}
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.SingleOrDefault();
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
var first = true;
var result = default(T);
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
if (!first)
{
ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would
}
first = false;
result = v;
}
}
return result;
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector)
{
return ToDictionary(immutableArray, keySelector, EqualityComparer<TKey>.Default);
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TElement">The type of the element.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="elementSelector">The element selector.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector)
{
return ToDictionary(immutableArray, keySelector, elementSelector, EqualityComparer<TKey>.Default);
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="comparer">The comparer to initialize the dictionary with.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
Requires.NotNull(keySelector, "keySelector");
var result = new Dictionary<TKey, T>(comparer);
foreach (var v in immutableArray)
{
result.Add(keySelector(v), v);
}
return result;
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TElement">The type of the element.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="elementSelector">The element selector.</param>
/// <param name="comparer">The comparer to initialize the dictionary with.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
Requires.NotNull(keySelector, "keySelector");
Requires.NotNull(elementSelector, "elementSelector");
var result = new Dictionary<TKey, TElement>(immutableArray.Length, comparer);
foreach (var v in immutableArray.array)
{
result.Add(keySelector(v), elementSelector(v));
}
return result;
}
/// <summary>
/// Copies the contents of this array to a mutable array.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <returns>The newly instantiated array.</returns>
[Pure]
public static T[] ToArray<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
if (immutableArray.array.Length == 0)
{
return ImmutableArray<T>.Empty.array;
}
return (T[])immutableArray.array.Clone();
}
#endregion
#region ImmutableArray<T>.Builder extensions
/// <summary>
/// Returns the first element in the collection.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception>
[Pure]
public static T First<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
if (!builder.Any())
{
throw new InvalidOperationException();
}
return builder[0];
}
/// <summary>
/// Returns the first element in the collection, or the default value if the collection is empty.
/// </summary>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Any() ? builder[0] : default(T);
}
/// <summary>
/// Returns the last element in the collection.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception>
[Pure]
public static T Last<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
if (!builder.Any())
{
throw new InvalidOperationException();
}
return builder[builder.Count - 1];
}
/// <summary>
/// Returns the last element in the collection, or the default value if the collection is empty.
/// </summary>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Any() ? builder[builder.Count - 1] : default(T);
}
/// <summary>
/// Returns a value indicating whether this collection contains any elements.
/// </summary>
[Pure]
public static bool Any<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Count > 0;
}
#endregion
#region Private Implementation Details
/// <summary>Provides the core iterator implementation of <see cref="SelectMany"/>.</summary>
private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(
this ImmutableArray<TSource> immutableArray,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
foreach (TSource item in immutableArray.array)
{
foreach (TCollection result in collectionSelector(item))
{
yield return resultSelector(item, result);
}
}
}
#endregion
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
namespace RazorDBx.C5
{
struct RecConst
{
public const int HASHFACTOR = 387281;
}
/// <summary>
/// A generic record type with two fields.
/// <para>
/// Equality is defined field by field, using the <code>Equals</code> method
/// inherited from <code>System.Object</code> (i.e. using <see cref="T:C5.NaturalEqualityComparer`1"/>).
/// </para>
/// <para>
/// This type is similar to <see cref="T:C5.KeyValuePair`2"/>, but the latter
/// uses <see cref="P:C5.EqualityComparer`1.Default"/> to define field equality instead of <see cref="T:C5.NaturalEqualityComparer`1"/>.
/// </para>
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
public struct Rec<T1, T2> : IEquatable<Rec<T1, T2>>, IShowable
{
/// <summary>
///
/// </summary>
public readonly T1 X1;
/// <summary>
///
/// </summary>
public readonly T2 X2;
/// <summary>
///
/// </summary>
/// <param name="x1"></param>
/// <param name="x2"></param>
public Rec(T1 x1, T2 x2)
{
this.X1 = x1; this.X2 = x2;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Rec<T1, T2> other)
{
return
(X1 == null ? other.X1 == null : X1.Equals(other.X1)) &&
(X2 == null ? other.X2 == null : X2.Equals(other.X2))
;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return obj is Rec<T1, T2> ? Equals((Rec<T1, T2>)obj) : false;
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator ==(Rec<T1, T2> record1, Rec<T1, T2> record2)
{
return record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator !=(Rec<T1, T2> record1, Rec<T1, T2> record2)
{
return !record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
//TODO: don't use 0 as hashcode for null, but something else!
int hashcode = X1 == null ? 0 : X1.GetHashCode();
hashcode = hashcode * RecConst.HASHFACTOR + (X2 == null ? 0 : X2.GetHashCode());
return hashcode;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("({0}, {1})", X1, X2);
}
#region IShowable Members
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
bool incomplete = true;
stringbuilder.Append("(");
rest -= 2;
try
{
if (incomplete = !Showing.Show(X1, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X2, stringbuilder, ref rest, formatProvider))
return false;
}
finally
{
if (incomplete)
{
stringbuilder.Append("...");
rest -= 3;
}
stringbuilder.Append(")");
}
return true;
}
#endregion
#region IFormattable Members
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return Showing.ShowString(this, format, formatProvider);
}
#endregion
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
public struct Rec<T1, T2, T3> : IEquatable<Rec<T1, T2, T3>>, IShowable
{
/// <summary>
///
/// </summary>
public readonly T1 X1;
/// <summary>
///
/// </summary>
public readonly T2 X2;
/// <summary>
///
/// </summary>
public readonly T3 X3;
/// <summary>
///
/// </summary>
/// <param name="x1"></param>
/// <param name="x2"></param>
/// <param name="x3"></param>
public Rec(T1 x1, T2 x2, T3 x3)
{
this.X1 = x1; this.X2 = x2; this.X3 = x3;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Rec<T1, T2, T3> other)
{
return
(X1 == null ? other.X1 == null : X1.Equals(other.X1)) &&
(X2 == null ? other.X2 == null : X2.Equals(other.X2)) &&
(X3 == null ? other.X3 == null : X3.Equals(other.X3))
;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return obj is Rec<T1, T2, T3> ? Equals((Rec<T1, T2, T3>)obj) : false;
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator ==(Rec<T1, T2, T3> record1, Rec<T1, T2, T3> record2)
{
return record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator !=(Rec<T1, T2, T3> record1, Rec<T1, T2, T3> record2)
{
return !record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
//TODO: don't use 0 as hashcode for null, but something else!
int hashcode = X1 == null ? 0 : X1.GetHashCode();
hashcode = hashcode * RecConst.HASHFACTOR + (X2 == null ? 0 : X2.GetHashCode());
hashcode = hashcode * RecConst.HASHFACTOR + (X3 == null ? 0 : X3.GetHashCode());
return hashcode;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("({0}, {1}, {2})", X1, X2, X3);
}
#region IShowable Members
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
bool incomplete = true;
stringbuilder.Append("(");
rest -= 2;
try
{
if (incomplete = !Showing.Show(X1, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X2, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X3, stringbuilder, ref rest, formatProvider))
return false;
}
finally
{
if (incomplete)
{
stringbuilder.Append("...");
rest -= 3;
}
stringbuilder.Append(")");
}
return true;
}
#endregion
#region IFormattable Members
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return Showing.ShowString(this, format, formatProvider);
}
#endregion
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
public struct Rec<T1, T2, T3, T4> : IEquatable<Rec<T1, T2, T3, T4>>, IShowable
{
/// <summary>
///
/// </summary>
public readonly T1 X1;
/// <summary>
///
/// </summary>
public readonly T2 X2;
/// <summary>
///
/// </summary>
public readonly T3 X3;
/// <summary>
///
/// </summary>
public readonly T4 X4;
/// <summary>
///
/// </summary>
/// <param name="x1"></param>
/// <param name="x2"></param>
/// <param name="x3"></param>
/// <param name="x4"></param>
public Rec(T1 x1, T2 x2, T3 x3, T4 x4)
{
this.X1 = x1; this.X2 = x2; this.X3 = x3; this.X4 = x4;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Rec<T1, T2, T3, T4> other)
{
return
(X1 == null ? other.X1 == null : X1.Equals(other.X1)) &&
(X2 == null ? other.X2 == null : X2.Equals(other.X2)) &&
(X3 == null ? other.X3 == null : X3.Equals(other.X3)) &&
(X4 == null ? other.X4 == null : X4.Equals(other.X4))
;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return obj is Rec<T1, T2, T3, T4> ? Equals((Rec<T1, T2, T3, T4>)obj) : false;
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator ==(Rec<T1, T2, T3, T4> record1, Rec<T1, T2, T3, T4> record2)
{
return record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <param name="record1"></param>
/// <param name="record2"></param>
/// <returns></returns>
public static bool operator !=(Rec<T1, T2, T3, T4> record1, Rec<T1, T2, T3, T4> record2)
{
return !record1.Equals(record2);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
//TODO: don't use 0 as hashcode for null, but something else!
int hashcode = X1 == null ? 0 : X1.GetHashCode();
hashcode = hashcode * RecConst.HASHFACTOR + (X2 == null ? 0 : X2.GetHashCode());
hashcode = hashcode * RecConst.HASHFACTOR + (X3 == null ? 0 : X3.GetHashCode());
hashcode = hashcode * RecConst.HASHFACTOR + (X4 == null ? 0 : X4.GetHashCode());
return hashcode;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("({0}, {1}, {2}, {3})", X1, X2, X3, X4);
}
#region IShowable Members
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
bool incomplete = true;
stringbuilder.Append("(");
rest -= 2;
try
{
if (incomplete = !Showing.Show(X1, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X2, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X3, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(", ");
rest -= 2;
if (incomplete = !Showing.Show(X4, stringbuilder, ref rest, formatProvider))
return false;
}
finally
{
if (incomplete)
{
stringbuilder.Append("...");
rest -= 3;
}
stringbuilder.Append(")");
}
return true;
}
#endregion
#region IFormattable Members
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return Showing.ShowString(this, format, formatProvider);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;
using StackExchange.Redis.Profiling;
namespace Microsoft.AspNetCore.SignalR.Tests
{
public class TestConnectionMultiplexer : IConnectionMultiplexer
{
public string ClientName => throw new NotImplementedException();
public string Configuration => throw new NotImplementedException();
public int TimeoutMilliseconds => throw new NotImplementedException();
public long OperationCount => throw new NotImplementedException();
public bool PreserveAsyncOrder { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public bool IsConnected => true;
public bool IncludeDetailInExceptions { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int StormLogThreshold { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public bool IsConnecting => throw new NotImplementedException();
public event EventHandler<RedisErrorEventArgs> ErrorMessage
{
add { }
remove { }
}
public event EventHandler<ConnectionFailedEventArgs> ConnectionFailed
{
add { }
remove { }
}
public event EventHandler<InternalErrorEventArgs> InternalError
{
add { }
remove { }
}
public event EventHandler<ConnectionFailedEventArgs> ConnectionRestored
{
add { }
remove { }
}
public event EventHandler<EndPointEventArgs> ConfigurationChanged
{
add { }
remove { }
}
public event EventHandler<EndPointEventArgs> ConfigurationChangedBroadcast
{
add { }
remove { }
}
public event EventHandler<HashSlotMovedEventArgs> HashSlotMoved
{
add { }
remove { }
}
private readonly TestRedisServer _server;
public TestConnectionMultiplexer(TestRedisServer server)
{
_server = server;
}
public void BeginProfiling(object forContext)
{
throw new NotImplementedException();
}
public void Close(bool allowCommandsToComplete = true)
{
throw new NotImplementedException();
}
public Task CloseAsync(bool allowCommandsToComplete = true)
{
throw new NotImplementedException();
}
public bool Configure(TextWriter log = null)
{
throw new NotImplementedException();
}
public Task<bool> ConfigureAsync(TextWriter log = null)
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true)
{
throw new NotImplementedException();
}
public ServerCounters GetCounters()
{
throw new NotImplementedException();
}
public IDatabase GetDatabase(int db = -1, object asyncState = null)
{
throw new NotImplementedException();
}
public EndPoint[] GetEndPoints(bool configuredOnly = false)
{
throw new NotImplementedException();
}
public IServer GetServer(string host, int port, object asyncState = null)
{
throw new NotImplementedException();
}
public IServer GetServer(string hostAndPort, object asyncState = null)
{
throw new NotImplementedException();
}
public IServer GetServer(IPAddress host, int port)
{
throw new NotImplementedException();
}
public IServer GetServer(EndPoint endpoint, object asyncState = null)
{
throw new NotImplementedException();
}
public string GetStatus()
{
throw new NotImplementedException();
}
public void GetStatus(TextWriter log)
{
throw new NotImplementedException();
}
public string GetStormLog()
{
throw new NotImplementedException();
}
public ISubscriber GetSubscriber(object asyncState = null)
{
return new TestSubscriber(_server);
}
public int HashSlot(RedisKey key)
{
throw new NotImplementedException();
}
public long PublishReconfigure(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task<long> PublishReconfigureAsync(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public void ResetStormLog()
{
throw new NotImplementedException();
}
public void Wait(Task task)
{
throw new NotImplementedException();
}
public T Wait<T>(Task<T> task)
{
throw new NotImplementedException();
}
public void WaitAll(params Task[] tasks)
{
throw new NotImplementedException();
}
public void RegisterProfiler(Func<ProfilingSession> profilingSessionProvider)
{
throw new NotImplementedException();
}
public int GetHashSlot(RedisKey key)
{
throw new NotImplementedException();
}
public void ExportConfiguration(Stream destination, ExportOptions options = (ExportOptions)(-1))
{
throw new NotImplementedException();
}
}
public class TestRedisServer
{
private readonly ConcurrentDictionary<RedisChannel, List<(int, Action<RedisChannel, RedisValue>)>> _subscriptions =
new ConcurrentDictionary<RedisChannel, List<(int, Action<RedisChannel, RedisValue>)>>();
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{
if (_subscriptions.TryGetValue(channel, out var handlers))
{
foreach (var (_, handler) in handlers)
{
handler(channel, message);
}
}
return handlers != null ? handlers.Count : 0;
}
public void Subscribe(ChannelMessageQueue messageQueue, int subscriberId, CommandFlags flags = CommandFlags.None)
{
Action<RedisChannel, RedisValue> handler = (channel, value) =>
{
// Workaround for https://github.com/StackExchange/StackExchange.Redis/issues/969
// ChannelMessageQueue isn't mockable currently, this works around that by using private reflection
typeof(ChannelMessageQueue).GetMethod("Write", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(messageQueue, new object[] { channel, value });
};
_subscriptions.AddOrUpdate(messageQueue.Channel, _ => new List<(int, Action<RedisChannel, RedisValue>)> { (subscriberId, handler) }, (_, list) =>
{
list.Add((subscriberId, handler));
return list;
});
}
public void Unsubscribe(RedisChannel channel, int subscriberId, CommandFlags flags = CommandFlags.None)
{
if (_subscriptions.TryGetValue(channel, out var list))
{
list.RemoveAll((item) => item.Item1 == subscriberId);
}
}
}
public class TestSubscriber : ISubscriber
{
private static int StaticId;
private readonly int _id;
private readonly TestRedisServer _server;
public ConnectionMultiplexer Multiplexer => throw new NotImplementedException();
IConnectionMultiplexer IRedisAsync.Multiplexer => throw new NotImplementedException();
public TestSubscriber(TestRedisServer server)
{
_server = server;
_id = Interlocked.Increment(ref StaticId);
}
public EndPoint IdentifyEndpoint(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task<EndPoint> IdentifyEndpointAsync(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public bool IsConnected(RedisChannel channel = default)
{
throw new NotImplementedException();
}
public TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{
return _server.Publish(channel, message, flags);
}
public async Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{
await Task.Yield();
return Publish(channel, message, flags);
}
public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None)
{
Subscribe(channel, handler, flags);
return Task.CompletedTask;
}
public EndPoint SubscribedEndpoint(RedisChannel channel)
{
throw new NotImplementedException();
}
public bool TryWait(Task task)
{
throw new NotImplementedException();
}
public void Unsubscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
{
_server.Unsubscribe(channel, _id, flags);
}
public void UnsubscribeAll(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task UnsubscribeAllAsync(CommandFlags flags = CommandFlags.None)
{
throw new NotImplementedException();
}
public Task UnsubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
{
Unsubscribe(channel, handler, flags);
return Task.CompletedTask;
}
public void Wait(Task task)
{
throw new NotImplementedException();
}
public T Wait<T>(Task<T> task)
{
throw new NotImplementedException();
}
public void WaitAll(params Task[] tasks)
{
throw new NotImplementedException();
}
public ChannelMessageQueue Subscribe(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
// Workaround for https://github.com/StackExchange/StackExchange.Redis/issues/969
var redisSubscriberType = typeof(RedisChannel).Assembly.GetType("StackExchange.Redis.RedisSubscriber");
var ctor = typeof(ChannelMessageQueue).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
binder: null,
new Type[] { typeof(RedisChannel).MakeByRefType(), redisSubscriberType }, modifiers: null);
var queue = (ChannelMessageQueue)ctor.Invoke(new object[] { channel, null });
_server.Subscribe(queue, _id);
return queue;
}
public Task<ChannelMessageQueue> SubscribeAsync(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
var t = Subscribe(channel, flags);
return Task.FromResult(t);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertVector128Int161()
{
var test = new ImmBinaryOpTest__InsertVector128Int161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__InsertVector128Int161
{
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128Int161 testClass)
{
var result = Avx.InsertVector128(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector128<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static ImmBinaryOpTest__InsertVector128Int161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public ImmBinaryOpTest__InsertVector128Int161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.InsertVector128(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.InsertVector128(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Int16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.InsertVector128(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Int16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.InsertVector128(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__InsertVector128Int161();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.InsertVector128(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 8 ? left[i] : right[i-8]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<Int16>(Vector256<Int16>.1, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
namespace Entitas {
/// Implement this interface if you want to create a system which needs a
/// reference to a pool. Recommended way to create systems in general:
/// pool.CreateSystem(new MySystem());
/// Calling pool.CreateSystem(new MySystem()) will automatically inject
/// the pool if ISetPool is implemented.
/// It's recommended to pass in the pool as a dependency using ISetPool
/// rather than using Pools.sharedInstance.pool directly within the system
/// to avoid tight coupling.
public interface ISetPool {
void SetPool(Pool pool);
}
/// Implement this interface if you want to create a system which needs a
/// reference to pools. Recommended way to create systems in general:
/// pool.CreateSystem(new MySystem());
/// Calling pool.CreateSystem(new MySystem()) will automatically inject
/// the pools if ISetPools is implemented.
/// It's recommended to pass in the pools as a dependency using ISetPools
/// rather than using Pools.sharedInstance directly within the system
/// to avoid tight coupling.
public interface ISetPools {
void SetPools(Pools pools);
}
public static class PoolExtension {
/// Returns all entities matching the specified matcher.
public static Entity[] GetEntities(this Pool pool, IMatcher matcher) {
return pool.GetGroup(matcher).GetEntities();
}
/// This is the recommended way to create systems.
/// It will inject the pool if ISetPool is implemented.
/// It will inject the Pools.sharedInstance if ISetPools is implemented.
/// It will automatically create a ReactiveSystem if it is a
/// IReactiveSystem, IMultiReactiveSystem or IEntityCollectorSystem.
public static ISystem CreateSystem(this Pool pool, ISystem system) {
return CreateSystem(pool, system, Pools.sharedInstance);
}
/// This is the recommended way to create systems.
/// It will inject the pool if ISetPool is implemented.
/// It will inject the pools if ISetPools is implemented.
public static ISystem CreateSystem(this Pool pool,
ISystem system,
Pools pools) {
SetPool(system, pool);
SetPools(system, pools);
return system;
}
/// This is the recommended way to create systems.
/// It will inject the pool if ISetPool is implemented.
/// It will inject the pools if ISetPools is implemented.
/// It will automatically create a ReactiveSystem if it is a
/// IReactiveSystem, IMultiReactiveSystem or IEntityCollectorSystem.
public static ISystem CreateSystem(this Pool pool,
IReactiveExecuteSystem system) {
return CreateSystem(pool, system, Pools.sharedInstance);
}
/// This is the recommended way to create systems.
/// It will inject the pool if ISetPool is implemented.
/// It will inject the pools if ISetPools is implemented.
/// It will automatically create a ReactiveSystem if it is a
/// IReactiveSystem, IMultiReactiveSystem or IEntityCollectorSystem.
public static ISystem CreateSystem(this Pool pool,
IReactiveExecuteSystem system,
Pools pools) {
SetPool(system, pool);
SetPools(system, pools);
var reactiveSystem = system as IReactiveSystem;
if(reactiveSystem != null) {
return new ReactiveSystem(pool, reactiveSystem);
}
var multiReactiveSystem = system as IMultiReactiveSystem;
if(multiReactiveSystem != null) {
return new ReactiveSystem(pool, multiReactiveSystem);
}
var entityCollectorSystem = system as IEntityCollectorSystem;
if(entityCollectorSystem != null) {
return new ReactiveSystem(entityCollectorSystem);
}
throw new EntitasException(
"Could not create ReactiveSystem for " + system + "!",
"The system has to implement IReactiveSystem, " +
"IMultiReactiveSystem or IEntityCollectorSystem."
);
}
/// This is the recommended way to create systems.
/// It will inject the pools if ISetPools is implemented.
public static ISystem CreateSystem(this Pools pools, ISystem system) {
SetPools(system, pools);
return system;
}
/// This is the recommended way to create systems.
/// It will inject the pools if ISetPools is implemented.
/// It will automatically create a ReactiveSystem
/// if it is a IEntityCollectorSystem.
public static ISystem CreateSystem(this Pools pools,
IReactiveExecuteSystem system) {
SetPools(system, pools);
var entityCollectorSystem = system as IEntityCollectorSystem;
if(entityCollectorSystem != null) {
return new ReactiveSystem(entityCollectorSystem);
}
throw new EntitasException(
"Could not create ReactiveSystem for " + system + "!",
"Only IEntityCollectorSystem is supported for " +
"pools.CreateSystem(system)."
);
}
[Obsolete("pools.CreateSystem(system) can not infer which pool to set for ISetPool!", true)]
public static ISystem CreateSystem(this Pools pools, ISetPool system) {
throw new EntitasException(
"pools.CreateSystem(" + system + ") can not infer which pool " +
"to set for ISetPool!",
"pools.CreateSystem(system) only supports IInitializeSystem, " +
"IExecuteSystem, ICleanupSystem, ITearDownSystem and " +
"IEntityCollectorSystem."
);
}
[Obsolete("pools.CreateSystem(system) can not infer which pool to use to create a ReactiveSystem!", true)]
public static ISystem CreateSystem(this Pools pools, IReactiveSystem system) {
throw new EntitasException(
"pools.CreateSystem(" + system + ") can not infer which pool " +
"to use to create a ReactiveSystem!",
"pools.CreateSystem(system) only supports IInitializeSystem, " +
"IExecuteSystem, ICleanupSystem, ITearDownSystem and " +
"IEntityCollectorSystem."
);
}
[Obsolete("pools.CreateSystem(system) can not infer which pool to use to create a ReactiveSystem!", true)]
public static ISystem CreateSystem(this Pools pools, IMultiReactiveSystem system) {
throw new EntitasException(
"pools.CreateSystem(" + system + ") can not infer which pool " +
"to use to create a ReactiveSystem!",
"pools.CreateSystem(system) only supports IInitializeSystem, " +
"IExecuteSystem, ICleanupSystem, ITearDownSystem and " +
"IEntityCollectorSystem."
);
}
/// This will set the pool if ISetPool is implemented.
public static void SetPool(ISystem system, Pool pool) {
var poolSystem = system as ISetPool;
if(poolSystem != null) {
poolSystem.SetPool(pool);
}
}
/// This will set the pools if ISetPools is implemented.
public static void SetPools(ISystem system, Pools pools) {
var poolsSystem = system as ISetPools;
if(poolsSystem != null) {
poolsSystem.SetPools(pools);
}
}
/// Creates an EntityCollector which observes all specified pools.
/// This is useful when you want to create an EntityCollector
/// for multiple pools which can be used with IEntityCollectorSystem.
public static EntityCollector CreateEntityCollector(
this Pool[] pools,
IMatcher matcher,
GroupEventType eventType = GroupEventType.OnEntityAdded) {
var groups = new Group[pools.Length];
var eventTypes = new GroupEventType[pools.Length];
for (int i = 0; i < pools.Length; i++) {
groups[i] = pools[i].GetGroup(matcher);
eventTypes[i] = eventType;
}
return new EntityCollector(groups, eventTypes);
}
/// Creates a new entity and adds copies of all
/// specified components to it.
/// If replaceExisting is true it will replace exisintg components.
public static Entity CloneEntity(this Pool pool,
Entity entity,
bool replaceExisting = false,
params int[] indices) {
var target = pool.CreateEntity();
entity.CopyTo(target, replaceExisting, indices);
return target;
}
}
}
| |
using UnityEngine;
public static class tk2dTextGeomGen
{
public class GeomData
{
internal tk2dTextMeshData textMeshData = null;
internal tk2dFontData fontInst = null;
internal string formattedText = "";
}
// Use this to get a correctly set up textgeomdata object
// This uses a static global tmpData object and is not thread safe
// Fortunately for us, neither is the rest of Unity.
public static GeomData Data(tk2dTextMeshData textMeshData, tk2dFontData fontData, string formattedText) {
tmpData.textMeshData = textMeshData;
tmpData.fontInst = fontData;
tmpData.formattedText = formattedText;
return tmpData;
}
private static GeomData tmpData = new GeomData();
/// <summary>
/// Calculates the mesh dimensions for the given string
/// and returns a width and height.
/// </summary>
public static Vector2 GetMeshDimensionsForString(string str, GeomData geomData)
{
tk2dTextMeshData data = geomData.textMeshData;
tk2dFontData _fontInst = geomData.fontInst;
float maxWidth = 0.0f;
float cursorX = 0.0f;
float cursorY = 0.0f;
bool ignoreNextCharacter = false;
int target = 0;
for (int i = 0; i < str.Length && target < data.maxChars; ++i)
{
if (ignoreNextCharacter) {
ignoreNextCharacter = false;
continue;
}
int idx = str[i];
if (idx == '\n')
{
maxWidth = Mathf.Max(cursorX, maxWidth);
cursorX = 0.0f;
cursorY -= (_fontInst.lineHeight + data.lineSpacing) * data.scale.y;
continue;
}
else if (data.inlineStyling)
{
if (idx == '^' && i + 1 < str.Length)
{
if (str[i + 1] == '^') {
ignoreNextCharacter = true;
} else {
int cmdLength = 0;
switch (str[i + 1]) {
case 'c': cmdLength = 5; break;
case 'C': cmdLength = 9; break;
case 'g': cmdLength = 9; break;
case 'G': cmdLength = 17; break;
}
i += cmdLength;
continue;
}
}
}
bool inlineHatChar = (idx == '^');
// Get the character from dictionary / array
tk2dFontChar chr;
if (_fontInst.useDictionary)
{
if (!_fontInst.charDict.ContainsKey(idx)) idx = 0;
chr = _fontInst.charDict[idx];
}
else
{
if (idx >= _fontInst.chars.Length) idx = 0; // should be space
chr = _fontInst.chars[idx];
}
if (inlineHatChar) idx = '^';
cursorX += (chr.advance + data.spacing) * data.scale.x;
if (data.kerning && i < str.Length - 1)
{
foreach (var k in _fontInst.kerning)
{
if (k.c0 == str[i] && k.c1 == str[i+1])
{
cursorX += k.amount * data.scale.x;
break;
}
}
}
++target;
}
maxWidth = Mathf.Max(cursorX, maxWidth);
cursorY -= (_fontInst.lineHeight + data.lineSpacing) * data.scale.y;
return new Vector2(maxWidth, cursorY);
}
public static float GetYAnchorForHeight(float textHeight, GeomData geomData)
{
tk2dTextMeshData data = geomData.textMeshData;
tk2dFontData _fontInst = geomData.fontInst;
int heightAnchor = (int)data.anchor / 3;
float lineHeight = (_fontInst.lineHeight + data.lineSpacing) * data.scale.y;
switch (heightAnchor)
{
case 0: return -lineHeight;
case 1:
{
float y = -textHeight / 2.0f - lineHeight;
if (_fontInst.version >= 2)
{
float ty = _fontInst.texelSize.y * data.scale.y;
return Mathf.Floor(y / ty) * ty;
}
else return y;
}
case 2: return -textHeight - lineHeight;
}
return -lineHeight;
}
public static float GetXAnchorForWidth(float lineWidth, GeomData geomData)
{
tk2dTextMeshData data = geomData.textMeshData;
tk2dFontData _fontInst = geomData.fontInst;
int widthAnchor = (int)data.anchor % 3;
switch (widthAnchor)
{
case 0: return 0.0f; // left
case 1: // center
{
float x = -lineWidth / 2.0f;
if (_fontInst.version >= 2)
{
float tx = _fontInst.texelSize.x * data.scale.x;
return Mathf.Floor(x / tx) * tx;
}
return x;
}
case 2: return -lineWidth; // right
}
return 0.0f;
}
static void PostAlignTextData(Vector3[] pos, int offset, int targetStart, int targetEnd, float offsetX)
{
for (int i = targetStart * 4; i < targetEnd * 4; ++i)
{
Vector3 v = pos[offset + i];
v.x += offsetX;
pos[offset + i] = v;
}
}
// Channel select color constants
static readonly Color32[] channelSelectColors = new Color32[] { new Color32(0,0,255,0), new Color(0,255,0,0), new Color(255,0,0,0), new Color(0,0,0,255) };
// Inline styling
static Color32 meshTopColor = new Color32(255, 255, 255, 255);
static Color32 meshBottomColor = new Color32(255, 255, 255, 255);
static float meshGradientTexU = 0.0f;
static int curGradientCount = 1;
static Color32 errorColor = new Color32(255, 0, 255, 255);
static int GetFullHexColorComponent(int c1, int c2) {
int result = 0;
if (c1 >= '0' && c1 <= '9') result += (c1 - '0') * 16;
else if (c1 >= 'a' && c1 <= 'f') result += (10 + c1 - 'a') * 16;
else if (c1 >= 'A' && c1 <= 'F') result += (10 + c1 - 'A') * 16;
else return -1;
if (c2 >= '0' && c2 <= '9') result += (c2 - '0');
else if (c2 >= 'a' && c2 <= 'f') result += (10 + c2 - 'a');
else if (c2 >= 'A' && c2 <= 'F') result += (10 + c2 - 'A');
else return -1;
return result;
}
static int GetCompactHexColorComponent(int c) {
if (c >= '0' && c <= '9') return (c - '0') * 17;
if (c >= 'a' && c <= 'f') return (10 + c - 'a') * 17;
if (c >= 'A' && c <= 'F') return (10 + c - 'A') * 17;
return -1;
}
static int GetStyleHexColor(string str, bool fullHex, ref Color32 color) {
int r, g, b, a;
if (fullHex) {
if (str.Length < 8) return 1;
r = GetFullHexColorComponent(str[0], str[1]);
g = GetFullHexColorComponent(str[2], str[3]);
b = GetFullHexColorComponent(str[4], str[5]);
a = GetFullHexColorComponent(str[6], str[7]);
} else {
if (str.Length < 4) return 1;
r = GetCompactHexColorComponent(str[0]);
g = GetCompactHexColorComponent(str[1]);
b = GetCompactHexColorComponent(str[2]);
a = GetCompactHexColorComponent(str[3]);
}
if (r == -1 || g == -1 || b == -1 || a == -1) {
return 1;
}
color = new Color32((byte)r, (byte)g, (byte)b, (byte)a);
return 0;
}
static int SetColorsFromStyleCommand(string args, bool twoColors, bool fullHex) {
int argLength = (twoColors ? 2 : 1) * (fullHex ? 8 : 4);
bool error = false;
if (args.Length >= argLength) {
if (GetStyleHexColor(args, fullHex, ref meshTopColor) != 0) {
error = true;
}
if (twoColors) {
string color2 = args.Substring (fullHex ? 8 : 4);
if (GetStyleHexColor(color2, fullHex, ref meshBottomColor) != 0) {
error = true;
}
}
else {
meshBottomColor = meshTopColor;
}
}
else {
error = true;
}
if (error) {
meshTopColor = meshBottomColor = errorColor;
}
return argLength;
}
static void SetGradientTexUFromStyleCommand(int arg) {
meshGradientTexU = (float)(arg - '0') / (float)((curGradientCount > 0) ? curGradientCount : 1);
}
static int HandleStyleCommand(string cmd) {
if (cmd.Length == 0) return 0;
int cmdSymbol = cmd[0];
string cmdArgs = cmd.Substring(1);
int cmdLength = 0;
switch (cmdSymbol) {
case 'c': cmdLength = 1 + SetColorsFromStyleCommand(cmdArgs, false, false); break;
case 'C': cmdLength = 1 + SetColorsFromStyleCommand(cmdArgs, false, true); break;
case 'g': cmdLength = 1 + SetColorsFromStyleCommand(cmdArgs, true, false); break;
case 'G': cmdLength = 1 + SetColorsFromStyleCommand(cmdArgs, true, true); break;
}
if (cmdSymbol >= '0' && cmdSymbol <= '9') {
SetGradientTexUFromStyleCommand(cmdSymbol);
cmdLength = 1;
}
return cmdLength;
}
public static void GetTextMeshGeomDesc(out int numVertices, out int numIndices, GeomData geomData)
{
tk2dTextMeshData data = geomData.textMeshData;
numVertices = data.maxChars * 4;
numIndices = data.maxChars * 6;
}
public static int SetTextMeshGeom(Vector3[] pos, Vector2[] uv, Vector2[] uv2, Color32[] color, int offset, GeomData geomData)
{
tk2dTextMeshData data = geomData.textMeshData;
tk2dFontData fontInst = geomData.fontInst;
string formattedText = geomData.formattedText;
meshTopColor = new Color32(255, 255, 255, 255);
meshBottomColor = new Color32(255, 255, 255, 255);
meshGradientTexU = (float)data.textureGradient / (float)((fontInst.gradientCount > 0) ? fontInst.gradientCount : 1);
curGradientCount = fontInst.gradientCount;
Vector2 dims = GetMeshDimensionsForString(geomData.formattedText, geomData);
float offsetY = GetYAnchorForHeight(dims.y, geomData);
float cursorX = 0.0f;
float cursorY = 0.0f;
int target = 0;
int alignStartTarget = 0;
for (int i = 0; i < formattedText.Length && target < data.maxChars; ++i)
{
int idx = formattedText[i];
tk2dFontChar chr;
bool inlineHatChar = (idx == '^');
if (fontInst.useDictionary)
{
if (!fontInst.charDict.ContainsKey(idx)) idx = 0;
chr = fontInst.charDict[idx];
}
else
{
if (idx >= fontInst.chars.Length) idx = 0; // should be space
chr = fontInst.chars[idx];
}
if (inlineHatChar) idx = '^';
if (idx == '\n')
{
float lineWidth = cursorX;
int alignEndTarget = target; // this is one after the last filled character
if (alignStartTarget != target)
{
float xOffset = GetXAnchorForWidth(lineWidth, geomData);
PostAlignTextData(pos, offset, alignStartTarget, alignEndTarget, xOffset);
}
alignStartTarget = target;
cursorX = 0.0f;
cursorY -= (fontInst.lineHeight + data.lineSpacing) * data.scale.y;
continue;
}
else if (data.inlineStyling)
{
if (idx == '^')
{
if (i + 1 < formattedText.Length && formattedText[i + 1] == '^') {
++i;
} else {
i += HandleStyleCommand(formattedText.Substring(i + 1));
continue;
}
}
}
pos[offset + target * 4 + 0] = new Vector3(cursorX + chr.p0.x * data.scale.x, offsetY + cursorY + chr.p0.y * data.scale.y, 0);
pos[offset + target * 4 + 1] = new Vector3(cursorX + chr.p1.x * data.scale.x, offsetY + cursorY + chr.p0.y * data.scale.y, 0);
pos[offset + target * 4 + 2] = new Vector3(cursorX + chr.p0.x * data.scale.x, offsetY + cursorY + chr.p1.y * data.scale.y, 0);
pos[offset + target * 4 + 3] = new Vector3(cursorX + chr.p1.x * data.scale.x, offsetY + cursorY + chr.p1.y * data.scale.y, 0);
if (chr.flipped)
{
uv[offset + target * 4 + 0] = new Vector2(chr.uv1.x, chr.uv1.y);
uv[offset + target * 4 + 1] = new Vector2(chr.uv1.x, chr.uv0.y);
uv[offset + target * 4 + 2] = new Vector2(chr.uv0.x, chr.uv1.y);
uv[offset + target * 4 + 3] = new Vector2(chr.uv0.x, chr.uv0.y);
}
else
{
uv[offset + target * 4 + 0] = new Vector2(chr.uv0.x, chr.uv0.y);
uv[offset + target * 4 + 1] = new Vector2(chr.uv1.x, chr.uv0.y);
uv[offset + target * 4 + 2] = new Vector2(chr.uv0.x, chr.uv1.y);
uv[offset + target * 4 + 3] = new Vector2(chr.uv1.x, chr.uv1.y);
}
if (fontInst.textureGradients)
{
uv2[offset + target * 4 + 0] = chr.gradientUv[0] + new Vector2(meshGradientTexU, 0);
uv2[offset + target * 4 + 1] = chr.gradientUv[1] + new Vector2(meshGradientTexU, 0);
uv2[offset + target * 4 + 2] = chr.gradientUv[2] + new Vector2(meshGradientTexU, 0);
uv2[offset + target * 4 + 3] = chr.gradientUv[3] + new Vector2(meshGradientTexU, 0);
}
if (fontInst.isPacked)
{
Color32 c = channelSelectColors[chr.channel];
color[offset + target * 4 + 0] = c;
color[offset + target * 4 + 1] = c;
color[offset + target * 4 + 2] = c;
color[offset + target * 4 + 3] = c;
}
else {
color[offset + target * 4 + 0] = meshTopColor;
color[offset + target * 4 + 1] = meshTopColor;
color[offset + target * 4 + 2] = meshBottomColor;
color[offset + target * 4 + 3] = meshBottomColor;
}
cursorX += (chr.advance + data.spacing) * data.scale.x;
if (data.kerning && i < formattedText.Length - 1)
{
foreach (var k in fontInst.kerning)
{
if (k.c0 == formattedText[i] && k.c1 == formattedText[i+1])
{
cursorX += k.amount * data.scale.x;
break;
}
}
}
++target;
}
if (alignStartTarget != target)
{
float lineWidth = cursorX;
int alignEndTarget = target;
float xOffset = GetXAnchorForWidth(lineWidth, geomData);
PostAlignTextData(pos, offset, alignStartTarget, alignEndTarget, xOffset);
}
for (int i = target; i < data.maxChars; ++i)
{
pos[offset + i * 4 + 0] = pos[offset + i * 4 + 1] = pos[offset + i * 4 + 2] = pos[offset + i * 4 + 3] = Vector3.zero;
uv[offset + i * 4 + 0] = uv[offset + i * 4 + 1] = uv[offset + i * 4 + 2] = uv[offset + i * 4 + 3] = Vector2.zero;
if (fontInst.textureGradients)
{
uv2[offset + i * 4 + 0] = uv2[offset + i * 4 + 1] = uv2[offset + i * 4 + 2] = uv2[offset + i * 4 + 3] = Vector2.zero;
}
if (!fontInst.isPacked)
{
color[offset + i * 4 + 0] = color[offset + i * 4 + 1] = meshTopColor;
color[offset + i * 4 + 2] = color[offset + i * 4 + 3] = meshBottomColor;
}
else
{
color[offset + i * 4 + 0] = color[offset + i * 4 + 1] = color[offset + i * 4 + 2] = color[offset + i * 4 + 3] = Color.clear;
}
}
return target;
}
public static void SetTextMeshIndices(int[] indices, int offset, int vStart, GeomData geomData, int target)
{
tk2dTextMeshData data = geomData.textMeshData;
for (int i = 0; i < data.maxChars; ++i)
{
indices[offset + i * 6 + 0] = vStart + i * 4 + 0;
indices[offset + i * 6 + 1] = vStart + i * 4 + 1;
indices[offset + i * 6 + 2] = vStart + i * 4 + 3;
indices[offset + i * 6 + 3] = vStart + i * 4 + 2;
indices[offset + i * 6 + 4] = vStart + i * 4 + 0;
indices[offset + i * 6 + 5] = vStart + i * 4 + 3;
}
}
}
| |
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 Knockout_Webmail.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using WSExample.Areas.HelpPage.Models;
namespace WSExample.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Internal
{
/// <summary>
/// This class is a convenient utility class to execute a certain asynchronous function with retries,
/// allowing to specify custom retry filters and policies.
/// </summary>
public static class AsyncExecutorWithRetries
{
public static readonly int INFINITE_RETRIES = -1;
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task ExecuteWithRetries(
Func<int, Task> action,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
Func<int, Task<bool>> function = async (int i) => { await action(i); return true; };
return ExecuteWithRetriesHelper<bool>(
function,
0,
0,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
null,
retryExceptionFilter,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
return ExecuteWithRetries<T>(
function,
0,
maxNumErrorTries,
null,
retryExceptionFilter,
maxExecutionTime,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
/// <param name="function">Function to execute</param>
/// <param name="maxNumSuccessTries">Maximal number of successful execution attempts.
/// ExecuteWithRetries will try to re-execute the given function again if directed so by retryValueFilter.
/// Set to -1 for unlimited number of success retries, until retryValueFilter is satisfied.
/// Set to 0 for only one success attempt, which will cause retryValueFilter to be ignored and the given function executed only once until first success.</param>
/// <param name="maxNumErrorTries">Maximal number of execution attempts due to errors.
/// Set to -1 for unlimited number of error retries, until retryExceptionFilter is satisfied.</param>
/// <param name="retryValueFilter">Filter function to indicate if successful execution should be retied.
/// Set to null to disable successful retries.</param>
/// <param name="retryExceptionFilter">Filter function to indicate if error execution should be retied.
/// Set to null to disable error retries.</param>
/// <param name="maxExecutionTime">The maximal execution time of the ExecuteWithRetries function.</param>
/// <param name="onSuccessBackOff">The backoff provider object, which determines how much to wait between success retries.</param>
/// <param name="onErrorBackOff">The backoff provider object, which determines how much to wait between error retries</param>
/// <returns></returns>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumSuccessTries,
int maxNumErrorTries,
Func<T, int, bool> retryValueFilter,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime = default(TimeSpan),
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
return ExecuteWithRetriesHelper<T>(
function,
0,
maxNumSuccessTries,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
retryValueFilter,
retryExceptionFilter,
onSuccessBackOff,
onErrorBackOff);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static async Task<T> ExecuteWithRetriesHelper<T>(
Func<int, Task<T>> function,
int callCounter,
int maxNumSuccessTries,
int maxNumErrorTries,
TimeSpan maxExecutionTime,
DateTime startExecutionTime,
Func<T, int, bool> retryValueFilter = null,
Func<Exception, int, bool> retryExceptionFilter = null,
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
T result = default(T);
ExceptionDispatchInfo lastExceptionInfo = null;
bool retry;
do
{
retry = false;
if (maxExecutionTime != Constants.INFINITE_TIMESPAN && maxExecutionTime != default(TimeSpan))
{
DateTime now = DateTime.UtcNow;
if (now - startExecutionTime > maxExecutionTime)
{
if (lastExceptionInfo == null)
{
throw new TimeoutException(
$"ExecuteWithRetries has exceeded its max execution time of {maxExecutionTime}. Now is {LogFormatter.PrintDate(now)}, started at {LogFormatter.PrintDate(startExecutionTime)}, passed {now - startExecutionTime}");
}
lastExceptionInfo.Throw();
}
}
int counter = callCounter;
try
{
callCounter++;
result = await function(counter);
lastExceptionInfo = null;
if (callCounter < maxNumSuccessTries || maxNumSuccessTries == INFINITE_RETRIES) // -1 for infinite retries
{
if (retryValueFilter != null)
retry = retryValueFilter(result, counter);
}
if (retry)
{
TimeSpan? delay = onSuccessBackOff?.Next(counter);
if (delay.HasValue)
{
await Task.Delay(delay.Value);
}
}
}
catch (Exception exc)
{
retry = false;
if (callCounter < maxNumErrorTries || maxNumErrorTries == INFINITE_RETRIES)
{
if (retryExceptionFilter != null)
retry = retryExceptionFilter(exc, counter);
}
if (!retry)
{
throw;
}
lastExceptionInfo = ExceptionDispatchInfo.Capture(exc);
TimeSpan? delay = onErrorBackOff?.Next(counter);
if (delay.HasValue)
{
await Task.Delay(delay.Value);
}
}
} while (retry);
return result;
}
}
// Allow multiple implementations of the backoff algorithm.
// For instance, ConstantBackoff variation that always waits for a fixed timespan,
// or a RateLimitingBackoff that keeps makes sure that some minimum time period occurs between calls to some API
// (especially useful if you use the same instance for multiple potentially simultaneous calls to ExecuteWithRetries).
// Implementations should be imutable.
// If mutable state is needed, extend the next function to pass the state from the caller.
// example: TimeSpan Next(int attempt, object state, out object newState);
public interface IBackoffProvider
{
TimeSpan Next(int attempt);
}
public class FixedBackoff : IBackoffProvider
{
private readonly TimeSpan fixedDelay;
public FixedBackoff(TimeSpan delay)
{
fixedDelay = delay;
}
public TimeSpan Next(int attempt)
{
return fixedDelay;
}
}
internal class ExponentialBackoff : IBackoffProvider
{
private readonly TimeSpan minDelay;
private readonly TimeSpan maxDelay;
private readonly TimeSpan step;
private readonly SafeRandom random;
public ExponentialBackoff(TimeSpan minDelay, TimeSpan maxDelay, TimeSpan step)
{
if (minDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be a positive number.");
if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("maxDelay", maxDelay, "ExponentialBackoff max delay must be a positive number.");
if (step <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("step", step, "ExponentialBackoff step must be a positive number.");
if (minDelay >= maxDelay) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be greater than max delay.");
this.minDelay = minDelay;
this.maxDelay = maxDelay;
this.step = step;
this.random = new SafeRandom();
}
public TimeSpan Next(int attempt)
{
TimeSpan currMax;
try
{
long multiple = checked(1 << attempt);
currMax = minDelay + step.Multiply(multiple); // may throw OverflowException
if (currMax <= TimeSpan.Zero)
throw new OverflowException();
}
catch (OverflowException)
{
currMax = maxDelay;
}
currMax = StandardExtensions.Min(currMax, maxDelay);
if (minDelay >= currMax) throw new ArgumentOutOfRangeException($"minDelay {minDelay}, currMax = {currMax}");
return random.NextTimeSpan(minDelay, currMax);
}
}
}
| |
// 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.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
public abstract class FieldInfo : MemberInfo
{
#region Static Members
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle));
FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
Type declaringType = f.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"),
f.Name, declaringType.GetGenericTypeDefinition()));
return f;
}
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo());
}
#endregion
#region Constructor
protected FieldInfo() { }
#endregion
public static bool operator ==(FieldInfo left, FieldInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeFieldInfo || right is RuntimeFieldInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(FieldInfo left, FieldInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type[] GetRequiredCustomModifiers()
{
throw new NotImplementedException();
}
public virtual Type[] GetOptionalCustomModifiers()
{
throw new NotImplementedException();
}
[CLSCompliant(false)]
public virtual void SetValueDirect(TypedReference obj, Object value)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
[CLSCompliant(false)]
public virtual Object GetValueDirect(TypedReference obj)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
public abstract RuntimeFieldHandle FieldHandle { get; }
public abstract Type FieldType { get; }
public abstract Object GetValue(Object obj);
public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
public abstract FieldAttributes Attributes { get; }
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null);
}
public bool IsPublic { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
public bool IsPrivate { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
public bool IsFamily { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
public bool IsAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
public bool IsFamilyAndAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
public bool IsFamilyOrAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
public bool IsStatic { get { return (Attributes & FieldAttributes.Static) != 0; } }
public bool IsInitOnly { get { return (Attributes & FieldAttributes.InitOnly) != 0; } }
public bool IsLiteral { get { return (Attributes & FieldAttributes.Literal) != 0; } }
public bool IsNotSerialized { get { return (Attributes & FieldAttributes.NotSerialized) != 0; } }
public bool IsSpecialName { get { return (Attributes & FieldAttributes.SpecialName) != 0; } }
public bool IsPinvokeImpl { get { return (Attributes & FieldAttributes.PinvokeImpl) != 0; } }
public virtual bool IsSecurityCritical
{
get { return FieldHandle.IsSecurityCritical(); }
}
public virtual bool IsSecuritySafeCritical
{
get { return FieldHandle.IsSecuritySafeCritical(); }
}
public virtual bool IsSecurityTransparent
{
get { return FieldHandle.IsSecurityTransparent(); }
}
#endregion
}
[Serializable]
internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
{
#region Private Data Members
private BindingFlags m_bindingFlags;
protected RuntimeTypeCache m_reflectedTypeCache;
protected RuntimeType m_declaringType;
#endregion
#region Constructor
protected RuntimeFieldInfo()
{
// Used for dummy head node during population
}
protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags)
{
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_reflectedTypeCache = reflectedTypeCache;
}
#endregion
#region NonPublic Members
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal abstract RuntimeModule GetRuntimeModule();
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Field; } }
public override Type ReflectedType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
public override Module Module { get { return GetRuntimeModule(); } }
#endregion
#region Object Overrides
public unsafe override String ToString()
{
return FieldType.FormatTypeName() + " " + Name;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region FieldInfo Overrides
// All implemented on derived classes
#endregion
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
MemberTypes.Field);
}
#endregion
}
[Serializable]
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
#endregion
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
private string m_name;
private RuntimeType m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
// Allow "value__"
if (m_declaringType.IsEnum)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
return false;
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
Type declaringType = DeclaringType;
bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
INVOCATION_FLAGS invocationFlags = 0;
// first take care of all the NO_INVOKE cases
if (
(declaringType != null && declaringType.ContainsGenericParameters) ||
(declaringType == null && Module.Assembly.ReflectionOnly) ||
(fIsReflectionOnlyType)
)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
// If the invocationFlags are still 0, then
// this should be an usable field, determine the other flags
if (invocationFlags == 0)
{
if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
// A public field is inaccesible to Transparent code if the field is Critical.
bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical;
bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck);
if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
// must be last to avoid threading problems
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
}
#endregion
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
}
}
#endregion
#region Internal Members
internal void CheckConsistency(Object target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg"));
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"),
Name, m_declaringType, target.GetType()));
}
}
}
}
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
if ((object)m == null)
return false;
return m.m_fieldHandle == m_fieldHandle;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && declaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
#region Security Check
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags);
#endregion
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
// UnsafeSetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
RuntimeType fieldType = (RuntimeType)FieldType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD));
return UnsafeGetValue(obj);
}
// UnsafeGetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
bool domainInitialized = false;
if (declaringType == null)
{
return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeFieldHandle.GetName(this);
return m_name;
}
}
internal String FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, Name);
}
}
public override int MetadataToken
{
get { return RuntimeFieldHandle.GetToken(this); }
}
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
}
#endregion
#region FieldInfo Overrides
public override Object GetValue(Object obj)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
}
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeFieldHandle(this);
}
}
internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
public override FieldAttributes Attributes
{
get
{
return m_fieldAttributes;
}
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
m_fieldType = new Signature(this, m_declaringType).FieldType;
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
}
#endregion
}
[Serializable]
internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
{
#region Private Data Members
private int m_tkField;
private string m_name;
private RuntimeType m_fieldType;
private FieldAttributes m_fieldAttributes;
#endregion
#region Constructor
internal MdFieldInfo(
int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
{
m_tkField = tkField;
m_name = null;
m_fieldAttributes = fieldAttributes;
}
#endregion
#region Internal Members
internal override bool CacheEquals(object o)
{
MdFieldInfo m = o as MdFieldInfo;
if ((object)m == null)
return false;
return m.m_tkField == m_tkField &&
m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
return m_name;
}
}
public override int MetadataToken { get { return m_tkField; } }
internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region FieldInfo Overrides
public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
return GetValue(null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public unsafe override Object GetValue(Object obj)
{
return GetValue(false);
}
public unsafe override Object GetRawConstantValue() { return GetValue(true); }
private unsafe Object GetValue(bool raw)
{
// Cannot cache these because they could be user defined non-agile enumerations
Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
if (value == DBNull.Value)
throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return value;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
{
ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
(int)fieldMarshal.Length, m_declaringType).FieldType;
}
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return EmptyArray<Type>.Value;
}
public override Type[] GetOptionalCustomModifiers()
{
return EmptyArray<Type>.Value;
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSpecialistPoolServiceClientTest
{
[xunit::FactAttribute]
public void GetSpecialistPoolRequestObject()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPool(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool response = client.GetSpecialistPool(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSpecialistPoolRequestObjectAsync()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPoolAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SpecialistPool>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool responseCallSettings = await client.GetSpecialistPoolAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SpecialistPool responseCancellationToken = await client.GetSpecialistPoolAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSpecialistPool()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPool(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool response = client.GetSpecialistPool(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSpecialistPoolAsync()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPoolAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SpecialistPool>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool responseCallSettings = await client.GetSpecialistPoolAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SpecialistPool responseCancellationToken = await client.GetSpecialistPoolAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSpecialistPoolResourceNames()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPool(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool response = client.GetSpecialistPool(request.SpecialistPoolName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSpecialistPoolResourceNamesAsync()
{
moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient> mockGrpcClient = new moq::Mock<SpecialistPoolService.SpecialistPoolServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
SpecialistPool expectedResponse = new SpecialistPool
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
DisplayName = "display_name137f65c2",
SpecialistManagersCount = 1389839351,
SpecialistManagerEmails =
{
"specialist_manager_emails54da434d",
},
PendingDataLabelingJobs =
{
"pending_data_labeling_jobsd91cc38b",
},
SpecialistWorkerEmails =
{
"specialist_worker_emailsac41cb4d",
},
};
mockGrpcClient.Setup(x => x.GetSpecialistPoolAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SpecialistPool>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SpecialistPoolServiceClient client = new SpecialistPoolServiceClientImpl(mockGrpcClient.Object, null);
SpecialistPool responseCallSettings = await client.GetSpecialistPoolAsync(request.SpecialistPoolName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SpecialistPool responseCancellationToken = await client.GetSpecialistPoolAsync(request.SpecialistPoolName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// #define STRATUS_EVENTS_DEBUG
namespace Stratus
{
using DelegateMap = Dictionary<string, List<Delegate>>;
using DelegateTypeList = List<Delegate>;
using DispatchMap = Dictionary<GameObject, Dictionary<string, List<Delegate>>>;
/// <summary>
/// The class which manages the overlying Stratus event system.
/// </summary>
[StratusSingleton("Stratus Event System", true, true)]
public class StratusEvents : StratusSingletonBehaviour<StratusEvents>
{
public class LoggingSetup
{
public bool construction = false;
public bool register = false;
public bool connect = true;
public bool dispatch = false;
}
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// Whether we are doing tracing for debugging purposes.
/// </summary>
public static LoggingSetup logging { get; } = new LoggingSetup();
/// <summary>
/// A map of all GameObjects connected to the event system and a map of delegates that are connected to them.
/// Whenever an event of a given type is sent to the GameObject, we invoke it on all delegates for a given type
/// (essentially a list of delegates for each type)
/// </summary>
private DispatchMap dispatchMap { get; set; } = new DispatchMap();
/// <summary>
/// A map of all components that have connected to a GameObject for specific events
/// </summary>
private Dictionary<MonoBehaviour, List<GameObject>> connectMap { get; set; } = new Dictionary<MonoBehaviour, List<GameObject>>();
/// <summary>
/// A list of all event types that are being watched for at the moment.
/// </summary>
private List<string> eventWatchList { get; set; } = new List<string>();
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
/// <summary>
/// Initializes the event system manager.
/// </summary>
protected override void OnAwake()
{
}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Connects to the event of a given object.
/// </summary>
/// <typeparam name="T">The event class. </typeparam>
/// <param name="gameObject">The GameObject we are connecting to whose events we are connecting to. </param>
/// <param name="memFunc">The member function to connect to. </param>
public static void Connect<T>(GameObject gameObject, Action<T> memFunc)
{
Type type = typeof(T);
string key = type.ToString();
// If the GameObject hasn't been registered yet, add its key
CheckRegistration(gameObject);
// If the event has no delegates yet, add it
if (!StratusEvents.instance.dispatchMap[gameObject].ContainsKey(key))
{
StratusEvents.instance.dispatchMap[gameObject].Add(key, new DelegateTypeList());
}
// If the delegate is already present, do not add it
if (StratusEvents.instance.dispatchMap[gameObject][key].Contains(memFunc))
{
return;
}
// Add the component's delegate onto the gameobject
AddDelegate(gameObject, key, memFunc);
// Record that this component has connected to this GameObject
Register((MonoBehaviour)memFunc.Target, gameObject);
#if STRATUS_EVENTS_DEBUG
Trace.Script(memFunc.ToString() + " has connected to " + gameObject.name);
//Trace.Script(obj.name + " now has '" + Events.Instance.DelegatesByType[obj].Count + "' delegates");
#endif
}
public static void Connect(GameObject gameObject, Action<Stratus.StratusEvent> memFunc, Type type)
{
string key = type.ToString();
// If the GameObject hasn't been registered yet, add its key
CheckRegistration(gameObject);
// If this GameObject's dispatch map has no delegates for this event type yet, create it
if (!StratusEvents.instance.dispatchMap[gameObject].ContainsKey(key))
{
StratusEvents.instance.dispatchMap[gameObject].Add(key, new DelegateTypeList());
}
// If the delegate is already present, do not add it
if (StratusEvents.instance.dispatchMap[gameObject][key].Contains(memFunc))
{
return;
}
// Add the component's delegate onto the gameobject
AddDelegate(gameObject, key, memFunc);
// Record that this component has connected to this GameObject
Register((MonoBehaviour)memFunc.Target, gameObject);
#if STRATUS_EVENTS_DEBUG
Trace.Script(memFunc.ToString() + " has connected to " + gameObject.name);
#endif
}
/// <summary>
/// Disconnects this component from all events it has subscribed to.
/// </summary>
/// <param name="component"></param>
public static void Disconnect(MonoBehaviour component)
{
if (isQuitting)
{
return;
}
// If the component is already connected and present in the event system
if (instance.connectMap.ContainsKey(component))
{
// For every gameobject that it has connected to
foreach (GameObject gameobj in instance.connectMap[component])
{
// Disconnect its delegates from it
DisconnectFromGameObject(component, gameobj);
}
}
// Remove the component from the event system
instance.connectMap.Remove(component);
}
/// <summary>
/// Disconnects this component from all events it has subscribed on
/// the given GameoObject.
/// </summary>
/// <param name="gameObj"></param>
/// <param name="component"></param>
public static void Disconnect(MonoBehaviour component, GameObject gameObj)
{
DisconnectFromGameObject(component, gameObj);
// Remove the gameobject from the component's list in the system
instance.connectMap[component].Remove(gameObj);
}
/// <summary>
/// Disconnects this component from all events it has subscribed on
/// the given GameoObject.
/// </summary>
/// <param name="gameObj"></param>
/// <param name="component"></param>
private static void DisconnectFromGameObject(Behaviour component, GameObject gameObj)
{
// If the GameObject has been removed previously...
if (!StratusEvents.instance.dispatchMap.ContainsKey(gameObj))
{
return;
}
// For every delegate this GameObject has
foreach (KeyValuePair<string, DelegateTypeList> pair in StratusEvents.instance.dispatchMap[gameObj])
{
// For every delegate in the list
foreach (Delegate deleg in pair.Value)
{
if ((MonoBehaviour)deleg.Target == component)
{
#if STRATUS_EVENTS_DEBUG
Trace.Script("Disconnecting <i>" + deleg.Method.Name + "</i> from " + gameObj.name);
#endif
// Remove this delegate
pair.Value.Remove(deleg);
break;
}
}
}
}
/// <summary>
/// Dispatches the given event of the specified type onto the object.
/// </summary>
/// <typeparam name="T">The event class.</typeparam>
/// <param name="obj">The object to which to connect to.</param>
/// <param name="e">The event to which to listen for.</param>
/// <param name="nextFrame">Whether to send this event on the next frame.</param>
public static void Dispatch<T>(GameObject obj, T e, bool nextFrame = false) where T : StratusEvent
{
string key = typeof(T).ToString();
#if STRATUS_EVENTS_DEBUG
// Trace.Script("'" + key + "' to '" + obj.name + "'");
#endif
// If this a delayed dispatch...
if (nextFrame)
{
instance.StartCoroutine(DispatchNextFrame<T>(obj, e));
}
// Check if the object has been registered onto the event system.
// If not, it will be.
CheckRegistration(obj);
// If there is no delegate registered to this object, do nothing.
if (!HasDelegate(obj, key))
{
#if STRATUS_EVENTS_DEBUG
//if (logging.Dispatch)
// Trace.Script("No delegate registered to " + obj.name + " for " + eventObj.ToString());
#endif
return;
}
// If we are watching events of this type
bool watching = false;
if (instance.eventWatchList.Contains(key))
{
watching = true;
}
// Invoke the method for every delegate
DelegateTypeList delegateMap = StratusEvents.instance.dispatchMap[obj][key];
DelegateTypeList delegatesToRemove = null;
foreach (Delegate deleg in delegateMap)
{
// If we are watching events of this type
if (watching)
{
StratusDebug.Log("Invoking member function on " + deleg.Target.ToString());
}
// Do a lazy delete if it has been nulled out?
if (IsNull(deleg.Method) || IsNull(deleg.Target))
{
if (delegatesToRemove == null)
{
delegatesToRemove = new DelegateTypeList();
}
delegatesToRemove.Add(deleg);
continue;
}
deleg.DynamicInvoke(e);
e.handled = true;
}
// If any delegates were found to be null, remove them (lazy delete)
if (delegatesToRemove != null)
{
foreach (Delegate deleg in delegatesToRemove)
{
delegateMap.Remove(deleg);
}
}
}
/// <summary>
/// Dispatches the given event of the specified type onto the object.
/// </summary>
/// <typeparam name="T">The event class.</typeparam>
/// <param name="obj">The object to which to connect to.</param>
/// <param name="e">The name of the event to which to listen for.</param>
/// <param name="nextFrame">Whether to send this event on the next frame.</param>
public static void Dispatch(GameObject obj, StratusEvent e, System.Type type, bool nextFrame = false)
{
string key = type.ToString();
#if STRATUS_EVENTS_DEBUG
if (logging.Connect)
Trace.Script("'" + key + "' to '" + obj.name + "'");
#endif
// If this a delayed dispatch...
if (nextFrame)
{
instance.StartCoroutine(DispatchNextFrame(obj, e, type));
}
// Check if the object has been registered onto the event system.
// If not, it will be.
CheckRegistration(obj);
// If there is no delegate registered to this object, do nothing.
if (!HasDelegate(obj, key))
{
#if STRATUS_EVENTS_DEBUG
if (logging.Dispatch)
Trace.Script("No delegate registered to " + obj.name + " for " + eventObj.ToString());
#endif
return;
}
// If we are watching events of this type
bool watching = false;
if (instance.eventWatchList.Contains(key))
{
watching = true;
}
// Invoke the method for every delegate
DelegateTypeList delegateMap = StratusEvents.instance.dispatchMap[obj][key];
DelegateTypeList delegatesToRemove = null;
foreach (Delegate deleg in delegateMap)
{
// If we are watching events of this type
if (watching)
{
StratusDebug.Log("Invoking member function on " + deleg.Target.ToString());
}
// Do a lazy delete if it has been nulled out?
if (IsNull(deleg.Method) || IsNull(deleg.Target))
{
if (delegatesToRemove == null)
{
delegatesToRemove = new DelegateTypeList();
}
delegatesToRemove.Add(deleg);
continue;
}
deleg.DynamicInvoke(e);
e.handled = true;
}
// If any delegates were found to be null, remove them (lazy delete)
if (delegatesToRemove != null)
{
foreach (Delegate deleg in delegatesToRemove)
{
delegateMap.Remove(deleg);
}
}
}
public static bool IsNull(object obj)
{
if (obj == null || (obj is UnityEngine.Object & obj.Equals(null)))
{
return true;
}
return false;
}
/// <summary>
/// Dispatches the event on the next frame.
/// </summary>
/// <typeparam name="T">The event class.</typeparam>
/// <param name="obj">The object to which to dispatch to.</param>
/// <param name="eventObj">The event object we are sending.</param>
/// <returns></returns>
public static IEnumerator DispatchNextFrame<T>(GameObject obj, T eventObj) where T : StratusEvent
{
// Wait 1 frame
yield return 0;
// Dispatch the event
Dispatch<T>(obj, eventObj);
}
/// <summary>
/// Dispatches the event on the next frame.
/// </summary>
/// <typeparam name="T">The event class.</typeparam>
/// <param name="obj">The object to which to dispatch to.</param>
/// <param name="eventObj">The event object we are sending.</param>
/// <returns></returns>
public static IEnumerator DispatchNextFrame(GameObject obj, StratusEvent eventObj, Type type)
{
// Wait 1 frame
yield return 0;
// Dispatch the event
Dispatch(obj, eventObj, type);
}
/// <summary>
/// Dispatches the given event of the specified type onto the GameObject amd all its children.
/// </summary>
/// <typeparam name="T">The event class. </typeparam>
/// <param name="gameObj">The GameObject to which to dispatch to.</param>
/// <param name="eventObj">The event object. </param>
public static void DispatchDown<T>(GameObject gameObj, T eventObj, bool nextFrame = false) where T : StratusEvent
{
foreach (GameObject child in gameObj.Children())
{
Dispatch<T>(child, eventObj, nextFrame);
}
}
/// <summary>
/// Dispatches an event up the tree on each parent recursively.
/// </summary>
/// <typeparam name="T">The event class. </typeparam>
/// <param name="gameObj">The GameObject to which to dispatch to.</param>
/// <param name="eventObj">The event object. </param>
public static void DispatchUp<T>(GameObject gameObj, T eventObj, bool nextFrame = false) where T : StratusEvent
{
Transform[] parents = gameObj.transform.GetComponentsInParent<Transform>();
foreach (Transform parent in parents)
{
Dispatch<T>(parent.gameObject, eventObj, nextFrame);
}
}
/// <summary>
/// Checks if the GameObject has been the given delegate.
/// </summary>
/// <param name="obj">A reference to the GameObject.</param>
/// <param name="key">The key to the delegate list.</param>
/// <returns>True if it has the delegate, false otherwise.</returns>
private static bool HasDelegate(GameObject obj, string key)
{
if (StratusEvents.instance.dispatchMap[obj] != null
&& StratusEvents.instance.dispatchMap[obj].ContainsKey(key))
{
return true;
}
#if STRATUS_EVENTS_DEBUG
if (logging.Dispatch)
{
Trace.Script("Events of type '" + key + "' for '" + obj.name + "' have no delegates yet!");
//string keys = "";
//foreach(var keyPresent in Events.Instance.DelegatesByType[obj])
//{
// keys += keyPresent.Key + " ";
//}
//Trace.Script("Its current events are: " + keys);
}
#endif
return false;
}
/// <summary>
/// Checks if the GameObject has been registered onto the event system.
/// </summary>
/// <param name="gameObj">A reference to the GameObject. </param>
private static void CheckRegistration(GameObject gameObj)
{
// If the GameObject hasn't registered yet, add its key
if (!StratusEvents.instance.dispatchMap.ContainsKey(gameObj))
{
StratusEvents.Connect(gameObj);
}
}
/// <summary>
/// Registers the MonoBehaviour to the event system.
/// </summary>
/// <param name="component"></param>
private static void Register(MonoBehaviour component, GameObject gameObject)
{
// If its component hasn't registered yet...
if (!instance.connectMap.ContainsKey(component))
{
// Record it
instance.connectMap.Add(component, new List<GameObject>());
}
// If we haven't recorded that this component has connected to this GameObject yet
if (!instance.connectMap[component].Contains(gameObject))
{
#if STRATUS_EVENTS_DEBUG
//Trace.Script(component.name + " has connected to " + gameObject.name);
#endif
instance.connectMap[component].Add(gameObject);
//component.gameObject.AddComponent<EventsRegistration>();
}
}
/// <summary>
/// Registers the GameObject to the event system.
/// </summary>
/// <param name="gameObject">The GameObject which is being registered. </param>
public static void Connect(GameObject gameObject)
{
#if STRATUS_EVENTS_DEBUGRATUS_EVENTS_DEBUG
//if (logging.Register)
// Trace.Script(gameObject.name + " has been registered to the event system");
#endif
StratusEvents.instance.dispatchMap.Add(gameObject, new DelegateMap());
gameObject.AddComponent<StratusEventsRegistration>();
}
/// <summary>
/// Returns true if this GameObjet has registered to the event system
/// </summary>
/// <param name="gameObject"></param>
/// <returns></returns>
public static bool IsConnected(GameObject gameObject)
{
return StratusEvents.instance.dispatchMap.ContainsKey(gameObject);
}
/// <summary>
/// Unregisters the GameObject from the event system.
/// </summary>
/// <param name="obj"></param>
public static void Disconnect(GameObject obj)
{
// Is this truly necessary, though?
if (isQuitting || StratusEvents.instance.dispatchMap == null)
{
return;
}
// Remove this GameObject from the event dispatch map
if (StratusEvents.instance.dispatchMap.ContainsKey(obj))
{
if (logging.register)
{
StratusDebug.Log(obj.name + " has been disconnected from the event system");
}
StratusEvents.instance.dispatchMap.Remove(obj);
}
}
/// <summary>
/// Adds the specified event to watch list, informing the user whenever
/// the event is being dispatched.
/// </summary>
/// <typeparam name="T">The event type.</typeparam>
public static void Watch<T>()
{
string type = typeof(T).ToString();
#if STRATUS_EVENTS_DEBUG
//if (logging.Dispatch)
// Trace.Script("Now watching for events of type '" + type + "'");
#endif
if (!instance.eventWatchList.Contains(type))
{
instance.eventWatchList.Add(type);
}
}
/// <summary>
/// Adds a member function delegate of a specific type onto the GameObject.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="gameObj"></param>
/// <param name="key"></param>
/// <param name="memFunc"></param>
private static void AddDelegate<T>(GameObject gameObj, string key, Action<T> memFunc)
{
#if STRATUS_EVENTS_DEBUG
//if (logging.Connect)
// Trace.Script("Adding delegate for event: " + key);
#endif
StratusEvents.instance.dispatchMap[gameObj][key].Add(memFunc);
}
public static IEnumerator WaitForFrames(int frameCount)
{
while (frameCount > 0)
{
frameCount--;
yield return null;
}
}
/// <summary>
/// Handles cleanup operations for MonoBehaviours that are connecting to
/// events in the Stratus Event System.
/// </summary>
public class Setup
{
private MonoBehaviour Owner;
public Setup(MonoBehaviour owner) { this.Owner = owner; }
~Setup() { this.Owner.Disconnect(); }
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: user-management/user_management_service.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace KillrVideo.UserManagement {
/// <summary>
/// The service responsible for managing user information
/// </summary>
public static class UserManagementService
{
static readonly string __ServiceName = "killrvideo.user_management.UserManagementService";
static readonly Marshaller<global::KillrVideo.UserManagement.CreateUserRequest> __Marshaller_CreateUserRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.CreateUserRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.UserManagement.CreateUserResponse> __Marshaller_CreateUserResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.CreateUserResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.UserManagement.VerifyCredentialsRequest> __Marshaller_VerifyCredentialsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.VerifyCredentialsRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.UserManagement.VerifyCredentialsResponse> __Marshaller_VerifyCredentialsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.VerifyCredentialsResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.UserManagement.GetUserProfileRequest> __Marshaller_GetUserProfileRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.GetUserProfileRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.UserManagement.GetUserProfileResponse> __Marshaller_GetUserProfileResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.UserManagement.GetUserProfileResponse.Parser.ParseFrom);
static readonly Method<global::KillrVideo.UserManagement.CreateUserRequest, global::KillrVideo.UserManagement.CreateUserResponse> __Method_CreateUser = new Method<global::KillrVideo.UserManagement.CreateUserRequest, global::KillrVideo.UserManagement.CreateUserResponse>(
MethodType.Unary,
__ServiceName,
"CreateUser",
__Marshaller_CreateUserRequest,
__Marshaller_CreateUserResponse);
static readonly Method<global::KillrVideo.UserManagement.VerifyCredentialsRequest, global::KillrVideo.UserManagement.VerifyCredentialsResponse> __Method_VerifyCredentials = new Method<global::KillrVideo.UserManagement.VerifyCredentialsRequest, global::KillrVideo.UserManagement.VerifyCredentialsResponse>(
MethodType.Unary,
__ServiceName,
"VerifyCredentials",
__Marshaller_VerifyCredentialsRequest,
__Marshaller_VerifyCredentialsResponse);
static readonly Method<global::KillrVideo.UserManagement.GetUserProfileRequest, global::KillrVideo.UserManagement.GetUserProfileResponse> __Method_GetUserProfile = new Method<global::KillrVideo.UserManagement.GetUserProfileRequest, global::KillrVideo.UserManagement.GetUserProfileResponse>(
MethodType.Unary,
__ServiceName,
"GetUserProfile",
__Marshaller_GetUserProfileRequest,
__Marshaller_GetUserProfileResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of UserManagementService</summary>
public abstract class UserManagementServiceBase
{
/// <summary>
/// Creates a new user
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.UserManagement.CreateUserResponse> CreateUser(global::KillrVideo.UserManagement.CreateUserRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Verify a user's username and password
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.UserManagement.VerifyCredentialsResponse> VerifyCredentials(global::KillrVideo.UserManagement.VerifyCredentialsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a user or group of user's profiles
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.UserManagement.GetUserProfileResponse> GetUserProfile(global::KillrVideo.UserManagement.GetUserProfileRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for UserManagementService</summary>
public class UserManagementServiceClient : ClientBase<UserManagementServiceClient>
{
/// <summary>Creates a new client for UserManagementService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public UserManagementServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for UserManagementService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public UserManagementServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UserManagementServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected UserManagementServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Creates a new user
/// </summary>
public virtual global::KillrVideo.UserManagement.CreateUserResponse CreateUser(global::KillrVideo.UserManagement.CreateUserRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateUser(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new user
/// </summary>
public virtual global::KillrVideo.UserManagement.CreateUserResponse CreateUser(global::KillrVideo.UserManagement.CreateUserRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateUser, null, options, request);
}
/// <summary>
/// Creates a new user
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.CreateUserResponse> CreateUserAsync(global::KillrVideo.UserManagement.CreateUserRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateUserAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new user
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.CreateUserResponse> CreateUserAsync(global::KillrVideo.UserManagement.CreateUserRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateUser, null, options, request);
}
/// <summary>
/// Verify a user's username and password
/// </summary>
public virtual global::KillrVideo.UserManagement.VerifyCredentialsResponse VerifyCredentials(global::KillrVideo.UserManagement.VerifyCredentialsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VerifyCredentials(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Verify a user's username and password
/// </summary>
public virtual global::KillrVideo.UserManagement.VerifyCredentialsResponse VerifyCredentials(global::KillrVideo.UserManagement.VerifyCredentialsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_VerifyCredentials, null, options, request);
}
/// <summary>
/// Verify a user's username and password
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.VerifyCredentialsResponse> VerifyCredentialsAsync(global::KillrVideo.UserManagement.VerifyCredentialsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VerifyCredentialsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Verify a user's username and password
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.VerifyCredentialsResponse> VerifyCredentialsAsync(global::KillrVideo.UserManagement.VerifyCredentialsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_VerifyCredentials, null, options, request);
}
/// <summary>
/// Gets a user or group of user's profiles
/// </summary>
public virtual global::KillrVideo.UserManagement.GetUserProfileResponse GetUserProfile(global::KillrVideo.UserManagement.GetUserProfileRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUserProfile(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a user or group of user's profiles
/// </summary>
public virtual global::KillrVideo.UserManagement.GetUserProfileResponse GetUserProfile(global::KillrVideo.UserManagement.GetUserProfileRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetUserProfile, null, options, request);
}
/// <summary>
/// Gets a user or group of user's profiles
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.GetUserProfileResponse> GetUserProfileAsync(global::KillrVideo.UserManagement.GetUserProfileRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUserProfileAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a user or group of user's profiles
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.UserManagement.GetUserProfileResponse> GetUserProfileAsync(global::KillrVideo.UserManagement.GetUserProfileRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetUserProfile, null, options, request);
}
protected override UserManagementServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new UserManagementServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(UserManagementServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CreateUser, serviceImpl.CreateUser)
.AddMethod(__Method_VerifyCredentials, serviceImpl.VerifyCredentials)
.AddMethod(__Method_GetUserProfile, serviceImpl.GetUserProfile).Build();
}
}
}
#endregion
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Markup.Data;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Markup.Xaml.Templates;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Portable.Xaml;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests.Xaml
{
public class BasicTests
{
[Fact]
public void Simple_Property_Is_Set()
{
var xaml = @"<ContentControl xmlns='https://github.com/avaloniaui' Content='Foo'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Foo", target.Content);
}
[Fact]
public void Default_Content_Property_Is_Set()
{
var xaml = @"<ContentControl xmlns='https://github.com/avaloniaui'>Foo</ContentControl>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Foo", target.Content);
}
[Fact]
public void AvaloniaProperty_Without_Getter_And_Setter_Is_Set()
{
var xaml =
@"<local:NonControl xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'
Foo='55' />";
var target = AvaloniaXamlLoader.Parse<NonControl>(xaml);
Assert.Equal(55, target.GetValue(NonControl.FooProperty));
}
[Fact]
public void AvaloniaProperty_With_Getter_And_No_Setter_Is_Set()
{
var xaml =
@"<local:NonControl xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'
Bar='bar' />";
var target = AvaloniaXamlLoader.Parse<NonControl>(xaml);
Assert.Equal("bar", target.Bar);
}
[Fact]
public void Attached_Property_Is_Set()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' TextBlock.FontSize='21'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal(21.0, TextBlock.GetFontSize(target));
}
[Fact]
public void Attached_Property_Is_Set_On_Control_Outside_Avalonia_Namspace()
{
// Test for issue #1548
var xaml =
@"<UserControl xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:TestControl Grid.Column='2' />
</UserControl>";
var target = AvaloniaXamlLoader.Parse<UserControl>(xaml);
Assert.Equal(2, Grid.GetColumn((TestControl)target.Content));
}
[Fact]
public void Attached_Property_With_Namespace_Is_Set()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'
xmlns:test='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'
test:BasicTestsAttachedPropertyHolder.Foo='Bar'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Bar", BasicTestsAttachedPropertyHolder.GetFoo(target));
}
[Fact]
public void Attached_Property_Supports_Binding()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' TextBlock.FontSize='{Binding}'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
target.DataContext = 21.0;
Assert.Equal(21.0, TextBlock.GetFontSize(target));
}
}
[Fact]
public void Attached_Property_In_Panel_Is_Set()
{
var xaml = @"
<Panel xmlns='https://github.com/avaloniaui'>
<ToolTip.Tip>Foo</ToolTip.Tip>
</Panel>";
var target = AvaloniaXamlLoader.Parse<Panel>(xaml);
Assert.Empty(target.Children);
Assert.Equal("Foo", ToolTip.GetTip(target));
}
[Fact]
public void NonExistent_Property_Throws()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' DoesntExist='foo'/>";
Assert.Throws<XamlObjectWriterException>(() => AvaloniaXamlLoader.Parse<ContentControl>(xaml));
}
[Fact]
public void Non_Attached_Property_With_Attached_Property_Syntax_Throws()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' TextBlock.Text='foo'/>";
Assert.Throws<XamlObjectWriterException>(() => AvaloniaXamlLoader.Parse<ContentControl>(xaml));
}
[Fact]
public void ContentControl_ContentTemplate_Is_Functional()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'>
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Text='Foo' />
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>";
var contentControl = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
var target = contentControl.ContentTemplate;
Assert.NotNull(target);
var txt = (TextBlock)target.Build(null);
Assert.Equal("Foo", txt.Text);
}
[Fact]
public void Named_Control_Is_Added_To_NameScope_Simple()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'>
<Button Name='button'>Foo</Button>
</UserControl>";
var control = AvaloniaXamlLoader.Parse<UserControl>(xaml);
var button = control.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
[Fact]
public void Direct_Content_In_ItemsControl_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ItemsControl Name='items'>
<ContentControl>Foo</ContentControl>
<ContentControl>Bar</ContentControl>
</ItemsControl>
</Window>";
var control = AvaloniaXamlLoader.Parse<Window>(xaml);
var itemsControl = control.FindControl<ItemsControl>("items");
Assert.NotNull(itemsControl);
var items = itemsControl.Items.Cast<ContentControl>().ToArray();
Assert.Equal("Foo", items[0].Content);
Assert.Equal("Bar", items[1].Content);
}
}
[Fact]
public void Panel_Children_Are_Added()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'>
<Panel Name='panel'>
<ContentControl Name='Foo' />
<ContentControl Name='Bar' />
</Panel>
</UserControl>";
var control = AvaloniaXamlLoader.Parse<UserControl>(xaml);
var panel = control.FindControl<Panel>("panel");
Assert.Equal(2, panel.Children.Count);
var foo = control.FindControl<ContentControl>("Foo");
var bar = control.FindControl<ContentControl>("Bar");
Assert.Contains(foo, panel.Children);
Assert.Contains(bar, panel.Children);
}
[Fact]
public void Grid_Row_Col_Definitions_Are_Built()
{
var xaml = @"
<Grid xmlns='https://github.com/avaloniaui'>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='100' />
<ColumnDefinition Width='Auto' />
<ColumnDefinition Width='*' />
<ColumnDefinition Width='100*' />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='100' />
<RowDefinition Height='Auto' />
<RowDefinition Height='*' />
<RowDefinition Height='100*' />
</Grid.RowDefinitions>
</Grid>";
var grid = AvaloniaXamlLoader.Parse<Grid>(xaml);
Assert.Equal(4, grid.ColumnDefinitions.Count);
Assert.Equal(4, grid.RowDefinitions.Count);
var expected1 = new GridLength(100);
var expected2 = GridLength.Auto;
var expected3 = new GridLength(1, GridUnitType.Star);
var expected4 = new GridLength(100, GridUnitType.Star);
Assert.Equal(expected1, grid.ColumnDefinitions[0].Width);
Assert.Equal(expected2, grid.ColumnDefinitions[1].Width);
Assert.Equal(expected3, grid.ColumnDefinitions[2].Width);
Assert.Equal(expected4, grid.ColumnDefinitions[3].Width);
Assert.Equal(expected1, grid.RowDefinitions[0].Height);
Assert.Equal(expected2, grid.RowDefinitions[1].Height);
Assert.Equal(expected3, grid.RowDefinitions[2].Height);
Assert.Equal(expected4, grid.RowDefinitions[3].Height);
}
[Fact]
public void Grid_Row_Col_Definitions_Are_Parsed()
{
var xaml = @"
<Grid xmlns='https://github.com/avaloniaui'
ColumnDefinitions='100,Auto,*,100*'
RowDefinitions='100,Auto,*,100*'>
</Grid>";
var grid = AvaloniaXamlLoader.Parse<Grid>(xaml);
Assert.Equal(4, grid.ColumnDefinitions.Count);
Assert.Equal(4, grid.RowDefinitions.Count);
var expected1 = new GridLength(100);
var expected2 = GridLength.Auto;
var expected3 = new GridLength(1, GridUnitType.Star);
var expected4 = new GridLength(100, GridUnitType.Star);
Assert.Equal(expected1, grid.ColumnDefinitions[0].Width);
Assert.Equal(expected2, grid.ColumnDefinitions[1].Width);
Assert.Equal(expected3, grid.ColumnDefinitions[2].Width);
Assert.Equal(expected4, grid.ColumnDefinitions[3].Width);
Assert.Equal(expected1, grid.RowDefinitions[0].Height);
Assert.Equal(expected2, grid.RowDefinitions[1].Height);
Assert.Equal(expected3, grid.RowDefinitions[2].Height);
Assert.Equal(expected4, grid.RowDefinitions[3].Height);
}
[Fact]
public void ControlTemplate_With_Nested_Child_Is_Operational()
{
var xaml = @"
<ControlTemplate xmlns='https://github.com/avaloniaui'>
<ContentControl Name='parent'>
<ContentControl Name='child' />
</ContentControl>
</ControlTemplate>
";
var template = AvaloniaXamlLoader.Parse<ControlTemplate>(xaml);
var parent = (ContentControl)template.Build(new ContentControl());
Assert.Equal("parent", parent.Name);
var child = parent.Content as ContentControl;
Assert.NotNull(child);
Assert.Equal("child", child.Name);
}
[Fact]
public void ControlTemplate_With_Panel_Children_Are_Added()
{
var xaml = @"
<ControlTemplate xmlns='https://github.com/avaloniaui'>
<Panel Name='panel'>
<ContentControl Name='Foo' />
<ContentControl Name='Bar' />
</Panel>
</ControlTemplate>
";
var template = AvaloniaXamlLoader.Parse<ControlTemplate>(xaml);
var panel = (Panel)template.Build(new ContentControl());
Assert.Equal(2, panel.Children.Count);
var foo = panel.Children[0];
var bar = panel.Children[1];
Assert.Equal("Foo", foo.Name);
Assert.Equal("Bar", bar.Name);
}
[Fact]
public void Named_x_Control_Is_Added_To_NameScope_Simple()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Button x:Name='button'>Foo</Button>
</UserControl>";
var control = AvaloniaXamlLoader.Parse<UserControl>(xaml);
var button = control.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
[Fact]
public void Standart_TypeConverter_Is_Used()
{
var xaml = @"<UserControl xmlns='https://github.com/avaloniaui' Width='200.5' />";
var control = AvaloniaXamlLoader.Parse<UserControl>(xaml);
Assert.Equal(200.5, control.Width);
}
[Fact]
public void Avalonia_TypeConverter_Is_Used()
{
var xaml = @"<UserControl xmlns='https://github.com/avaloniaui' Background='White' />";
var control = AvaloniaXamlLoader.Parse<UserControl>(xaml);
var bk = control.Background;
Assert.IsType<ImmutableSolidColorBrush>(bk);
Assert.Equal(Colors.White, (bk as ISolidColorBrush).Color);
}
[Fact]
public void Simple_Style_Is_Parsed()
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Style Selector='TextBlock'>
<Setter Property='Background' Value='White'/>
<Setter Property='Width' Value='100'/>
</Style>
</Styles>";
var styles = AvaloniaXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Equal(2, setters.Length);
Assert.Equal(TextBlock.BackgroundProperty, setters[0].Property);
Assert.Equal(Brushes.White.Color, ((ISolidColorBrush)setters[0].Value).Color);
Assert.Equal(TextBlock.WidthProperty, setters[1].Property);
Assert.Equal(100.0, setters[1].Value);
}
[Fact]
public void Style_Setter_With_AttachedProperty_Is_Parsed()
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Style Selector='ContentControl'>
<Setter Property='TextBlock.FontSize' Value='21'/>
</Style>
</Styles>";
var styles = AvaloniaXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Single(setters);
Assert.Equal(TextBlock.FontSizeProperty, setters[0].Property);
Assert.Equal(21.0, setters[0].Value);
}
[Fact]
public void Complex_Style_Is_Parsed()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'>
<Style Selector='CheckBox'>
<Setter Property='BorderBrush' Value='{DynamicResource ThemeBorderMidBrush}'/>
<Setter Property='BorderThickness' Value='{DynamicResource ThemeBorderThickness}'/>
<Setter Property='Template'>
<ControlTemplate>
<Grid ColumnDefinitions='Auto,*'>
<Border Name='border'
BorderBrush='{TemplateBinding BorderBrush}'
BorderThickness='{TemplateBinding BorderThickness}'
Width='18'
Height='18'
VerticalAlignment='Center'>
<Path Name='checkMark'
Fill='{StaticResource HighlightBrush}'
Width='11'
Height='10'
Stretch='Uniform'
HorizontalAlignment='Center'
VerticalAlignment='Center'
Data='M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z'/>
</Border>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'
ContentTemplate='{TemplateBinding ContentTemplate}'
Margin='4,0,0,0'
VerticalAlignment='Center'
Grid.Column='1'/>
</Grid>
</ControlTemplate>
</Setter>
</Style>
</Styles>
";
var styles = AvaloniaXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Equal(3, setters.Length);
Assert.Equal(CheckBox.BorderBrushProperty, setters[0].Property);
Assert.Equal(CheckBox.BorderThicknessProperty, setters[1].Property);
Assert.Equal(CheckBox.TemplateProperty, setters[2].Property);
Assert.IsType<ControlTemplate>(setters[2].Value);
}
}
[Fact]
public void Style_Resources_Are_Built()
{
var xaml = @"
<Style xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:sys='clr-namespace:System;assembly=mscorlib'>
<Style.Resources>
<SolidColorBrush x:Key='Brush'>White</SolidColorBrush>
<sys:Double x:Key='Double'>10</sys:Double>
</Style.Resources>
</Style>";
var style = AvaloniaXamlLoader.Parse<Style>(xaml);
Assert.True(style.Resources.Count > 0);
style.TryGetResource("Brush", out var brush);
Assert.NotNull(brush);
Assert.IsType<SolidColorBrush>(brush);
Assert.Equal(Colors.White, ((ISolidColorBrush)brush).Color);
style.TryGetResource("Double", out var d);
Assert.Equal(10.0, d);
}
[Fact]
public void StyleInclude_Is_Built()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<StyleInclude Source='resm:Avalonia.Themes.Default.ContextMenu.xaml?assembly=Avalonia.Themes.Default'/>
</Styles>";
var styles = AvaloniaXamlLoader.Parse<Styles>(xaml);
Assert.True(styles.Count == 1);
var styleInclude = styles.First() as StyleInclude;
Assert.NotNull(styleInclude);
var style = styleInclude.Loaded;
Assert.NotNull(style);
}
}
[Fact]
public void Simple_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' Content='{Binding}'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.Null(target.Content);
target.DataContext = "Foo";
Assert.Equal("Foo", target.Content);
}
}
[Fact]
public void Xaml_Binding_Is_Delayed()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' Content='{Binding}'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.Null(target.Content);
target.DataContext = "Foo";
Assert.Null(target.Content);
DelayedBinding.ApplyBindings(target);
Assert.Equal("Foo", target.Content);
}
}
[Fact]
public void Double_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' Width='{Binding}'/>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.Null(target.Content);
target.DataContext = 55.0;
Assert.Equal(55.0, target.Width);
}
}
[Fact]
public void Collection_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ItemsControl Name='itemsControl' Items='{Binding}'>
</ItemsControl>
</Window>
";
var target = AvaloniaXamlLoader.Parse<Window>(xaml);
Assert.NotNull(target.Content);
var itemsControl = target.FindControl<ItemsControl>("itemsControl");
var items = new string[] { "Foo", "Bar" };
//DelayedBinding.ApplyBindings(itemsControl);
target.DataContext = items;
Assert.Equal(items, itemsControl.Items);
}
}
[Fact]
public void Multi_Xaml_Binding_Is_Parsed()
{
var xaml =
@"<MultiBinding xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
Converter ='{x:Static BoolConverters.And}'>
<Binding Path='Foo' />
<Binding Path='Bar' />
</MultiBinding>";
var target = AvaloniaXamlLoader.Parse<MultiBinding>(xaml);
Assert.Equal(2, target.Bindings.Count);
Assert.Equal(BoolConverters.And, target.Converter);
var bindings = target.Bindings.Cast<Binding>().ToArray();
Assert.Equal("Foo", bindings[0].Path);
Assert.Equal("Bar", bindings[1].Path);
}
[Fact]
public void Control_Template_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Template>
<ControlTemplate TargetType='Window'>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'/>
</ControlTemplate>
</Window.Template>
</Window>";
var target = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target.Template);
Assert.Null(target.Presenter);
target.ApplyTemplate();
Assert.NotNull(target.Presenter);
target.Content = "Foo";
Assert.Equal("Foo", target.Presenter.Content);
}
}
[Fact]
public void Style_ControlTemplate_Is_Built()
{
var xaml = @"
<Style xmlns='https://github.com/avaloniaui' Selector='ContentControl'>
<Setter Property='Template'>
<ControlTemplate>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'
ContentTemplate='{TemplateBinding ContentTemplate}' />
</ControlTemplate>
</Setter>
</Style> ";
var style = AvaloniaXamlLoader.Parse<Style>(xaml);
Assert.Single(style.Setters);
var setter = (Setter)style.Setters.First();
Assert.Equal(ContentControl.TemplateProperty, setter.Property);
Assert.IsType<ControlTemplate>(setter.Value);
var template = (ControlTemplate)setter.Value;
var control = new ContentControl();
var result = (ContentPresenter)template.Build(control);
Assert.NotNull(result);
}
[Fact]
public void Named_Control_Is_Added_To_NameScope()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Button Name='button'>Foo</Button>
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var button = window.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
}
[Fact(Skip =
@"Doesn't work with Portable.xaml, it's working in different creation order -
Handled in test 'Control_Is_Added_To_Parent_Before_Final_EndInit'
do we need it?")]
public void Control_Is_Added_To_Parent_Before_Properties_Are_Set()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100'/>
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
var attached = tracker.Order.IndexOf("AttachedToLogicalTree");
var widthChanged = tracker.Order.IndexOf("Property Width Changed");
Assert.NotEqual(-1, attached);
Assert.NotEqual(-1, widthChanged);
Assert.True(attached < widthChanged);
}
}
[Fact]
public void Control_Is_Added_To_Parent_Before_Final_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100'/>
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
var attached = tracker.Order.IndexOf("AttachedToLogicalTree");
var endInit = tracker.Order.IndexOf("EndInit 0");
Assert.NotEqual(-1, attached);
Assert.NotEqual(-1, endInit);
Assert.True(attached < endInit);
}
}
[Fact]
public void All_Properties_Are_Set_Before_Final_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100' Height='100'
Tag='{Binding Height, RelativeSource={RelativeSource Self}}' />
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
//ensure binding is set and operational first
Assert.Equal(100.0, tracker.Tag);
Assert.Equal("EndInit 0", tracker.Order.Last());
}
}
[Fact]
public void BeginInit_Matches_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker />
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
Assert.Equal(0, tracker.InitState);
}
}
[Fact]
public void DeferedXamlLoader_Should_Preserve_NamespacesContext()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Tag='{x:Static local:NonControl.StringProperty}'/>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>";
var contentControl = AvaloniaXamlLoader.Parse<ContentControl>(xaml);
var template = contentControl.ContentTemplate;
Assert.NotNull(template);
var txt = (TextBlock)template.Build(null);
Assert.Equal((object)NonControl.StringProperty, txt.Tag);
}
[Fact]
public void Binding_To_List_AvaloniaProperty_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ListBox Items='{Binding Items}' SelectedItems='{Binding SelectedItems}'/>
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var listBox = (ListBox)window.Content;
var vm = new SelectedItemsViewModel()
{
Items = new string[] { "foo", "bar", "baz" }
};
window.DataContext = vm;
Assert.Equal(vm.Items, listBox.Items);
Assert.Equal(vm.SelectedItems, listBox.SelectedItems);
}
}
[Fact]
public void Element_Whitespace_Should_Be_Trimmed()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<TextBlock>
Hello World!
</TextBlock>
</Window>";
var window = AvaloniaXamlLoader.Parse<Window>(xaml);
var textBlock = (TextBlock)window.Content;
Assert.Equal("Hello World!", textBlock.Text);
}
}
[Fact]
public void Design_Mode_Properties_Should_Be_Ignored_At_Runtime_And_Set_In_Design_Mode()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DataContext='data-context'
d:DesignWidth='123'
d:DesignHeight='321'
>
</Window>";
foreach (var designMode in new[] {true, false})
{
var loader = new AvaloniaXamlLoader {IsDesignMode = designMode};
var obj = (Window)loader.Load(xaml);
var context = Design.GetDataContext(obj);
var width = Design.GetWidth(obj);
var height = Design.GetHeight(obj);
if (designMode)
{
Assert.Equal("data-context", context);
Assert.Equal(123, width);
Assert.Equal(321, height);
}
else
{
Assert.False(obj.IsSet(Design.DataContextProperty));
Assert.False(obj.IsSet(Design.WidthProperty));
Assert.False(obj.IsSet(Design.HeightProperty));
}
}
}
}
private class SelectedItemsViewModel : INotifyPropertyChanged
{
public string[] Items { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private IList _selectedItems = new AvaloniaList<string>();
public IList SelectedItems
{
get { return _selectedItems; }
set
{
_selectedItems = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItems)));
}
}
}
}
public class BasicTestsAttachedPropertyHolder
{
public static AvaloniaProperty<string> FooProperty =
AvaloniaProperty.RegisterAttached<BasicTestsAttachedPropertyHolder, AvaloniaObject, string>("Foo");
public static void SetFoo(AvaloniaObject target, string value) => target.SetValue(FooProperty, value);
public static string GetFoo(AvaloniaObject target) => (string)target.GetValue(FooProperty);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareLessThanOrderedScalarSingle()
{
var test = new BooleanComparisonOpTest__CompareLessThanOrderedScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanComparisonOpTest__CompareLessThanOrderedScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private BooleanComparisonOpTest__DataTable<Single> _dataTable;
static BooleanComparisonOpTest__CompareLessThanOrderedScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public BooleanComparisonOpTest__CompareLessThanOrderedScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new BooleanComparisonOpTest__DataTable<Single>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareLessThanOrderedScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareLessThanOrderedScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareLessThanOrderedScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
var result = Sse.CompareLessThanOrderedScalar(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareLessThanOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareLessThanOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareLessThanOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanComparisonOpTest__CompareLessThanOrderedScalarSingle();
var result = Sse.CompareLessThanOrderedScalar(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse.CompareLessThanOrderedScalar(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
if ((left[0] < right[0]) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareLessThanOrderedScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace WeifenLuo.WinFormsUI.Docking
{
public class VisualStudioToolStripRenderer : ToolStripProfessionalRenderer
{
private static Rectangle[] baseSizeGripRectangles =
{
new Rectangle(6,0,1,1),
new Rectangle(6,2,1,1),
new Rectangle(6,4,1,1),
new Rectangle(6,6,1,1),
new Rectangle(4,2,1,1),
new Rectangle(4,4,1,1),
new Rectangle(4,6,1,1),
new Rectangle(2,4,1,1),
new Rectangle(2,6,1,1),
new Rectangle(0,6,1,1)
};
private const int GRIP_PADDING = 4;
private SolidBrush _statusBarBrush;
private SolidBrush _statusGripBrush;
private SolidBrush _statusGripAccentBrush;
private SolidBrush _toolBarBrush;
private SolidBrush _gripBrush;
private Pen _toolBarBorderPen;
private VisualStudioColorTable _table;
private DockPanelColorPalette _palette;
public bool UseGlassOnMenuStrip { get; set; }
public VisualStudioToolStripRenderer(DockPanelColorPalette palette)
: base(new VisualStudioColorTable(palette))
{
_table = (VisualStudioColorTable)ColorTable;
_palette = palette;
RoundedEdges = false;
_statusBarBrush = new SolidBrush(palette.MainWindowStatusBarDefault.Background);
_statusGripBrush = new SolidBrush(palette.MainWindowStatusBarDefault.ResizeGrip);
_statusGripAccentBrush = new SolidBrush(palette.MainWindowStatusBarDefault.ResizeGripAccent);
_toolBarBrush = new SolidBrush(palette.CommandBarToolbarDefault.Background);
_gripBrush = new SolidBrush(palette.CommandBarToolbarDefault.Grip);
_toolBarBorderPen = new Pen(palette.CommandBarToolbarDefault.Border);
UseGlassOnMenuStrip = true;
}
#region Rendering Improvements (includes fixes for bugs occured when Windows Classic theme is on).
//*
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
// Do not draw disabled item background.
if (e.Item.Enabled)
{
bool isMenuDropDown = e.Item.Owner is MenuStrip;
if (isMenuDropDown && e.Item.Pressed)
{
base.OnRenderMenuItemBackground(e);
}
else if (e.Item.Selected)
{
// Rect of item's content area.
Rectangle contentRect = e.Item.ContentRectangle;
// Fix item rect.
Rectangle itemRect = isMenuDropDown
? new Rectangle(
contentRect.X + 2, contentRect.Y - 2,
contentRect.Width - 5, contentRect.Height + 3)
: new Rectangle(
contentRect.X, contentRect.Y - 1,
contentRect.Width, contentRect.Height + 1);
// Border pen and fill brush.
Color pen = ColorTable.MenuItemBorder;
Color brushBegin;
Color brushEnd;
if (isMenuDropDown)
{
brushBegin = ColorTable.MenuItemSelectedGradientBegin;
brushEnd = ColorTable.MenuItemSelectedGradientEnd;
}
else
{
brushBegin = ColorTable.MenuItemSelected;
brushEnd = Color.Empty;
}
DrawRectangle(e.Graphics, itemRect, brushBegin, brushEnd, pen, UseGlassOnMenuStrip);
}
}
}
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
var status = e.ToolStrip as StatusStrip;
if (status != null)
{
// IMPORTANT: left empty to remove white border.
return;
}
var context = e.ToolStrip as MenuStrip;
if (context != null)
{
base.OnRenderToolStripBorder(e);
return;
}
var drop = e.ToolStrip as ToolStripDropDown;
if (drop != null)
{
base.OnRenderToolStripBorder(e);
return;
}
var rect = e.ToolStrip.ClientRectangle;
e.Graphics.DrawRectangle(_toolBarBorderPen, new Rectangle(rect.Location, new Size(rect.Width - 1, rect.Height - 1)));
}
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
{
var status = e.ToolStrip as StatusStrip;
if (status != null)
{
base.OnRenderToolStripBackground(e);
return;
}
var context = e.ToolStrip as MenuStrip;
if (context != null)
{
base.OnRenderToolStripBackground(e);
return;
}
var drop = e.ToolStrip as ToolStripDropDown;
if (drop != null)
{
base.OnRenderToolStripBackground(e);
return;
}
e.Graphics.FillRectangle(_toolBarBrush, e.ToolStrip.ClientRectangle);
}
protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e)
{
// IMPORTANT: below code was taken from Microsoft's reference code (MIT license).
Graphics g = e.Graphics;
StatusStrip statusStrip = e.ToolStrip as StatusStrip;
// we have a set of stock rectangles. Translate them over to where the grip is to be drawn
// for the white set, then translate them up and right one pixel for the grey.
if (statusStrip != null)
{
Rectangle sizeGripBounds = statusStrip.SizeGripBounds;
if (!LayoutUtils.IsZeroWidthOrHeight(sizeGripBounds))
{
Rectangle[] whiteRectangles = new Rectangle[baseSizeGripRectangles.Length];
Rectangle[] greyRectangles = new Rectangle[baseSizeGripRectangles.Length];
for (int i = 0; i < baseSizeGripRectangles.Length; i++)
{
Rectangle baseRect = baseSizeGripRectangles[i];
if (statusStrip.RightToLeft == RightToLeft.Yes)
{
baseRect.X = sizeGripBounds.Width - baseRect.X - baseRect.Width;
}
baseRect.Offset(sizeGripBounds.X, sizeGripBounds.Bottom - 12 /*height of pyramid (10px) + 2px padding from bottom*/);
greyRectangles[i] = baseRect;
if (statusStrip.RightToLeft == RightToLeft.Yes)
{
baseRect.Offset(1, -1);
}
else
{
baseRect.Offset(-1, -1);
}
whiteRectangles[i] = baseRect;
}
g.FillRectangles(_statusGripAccentBrush, whiteRectangles);
g.FillRectangles(_statusGripBrush, greyRectangles);
}
}
}
protected override void OnRenderGrip(ToolStripGripRenderEventArgs e)
{
Graphics g = e.Graphics;
Rectangle bounds = e.GripBounds;
ToolStrip toolStrip = e.ToolStrip;
bool rightToLeft = (e.ToolStrip.RightToLeft == RightToLeft.Yes);
int height = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Height : bounds.Width;
int width = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Width : bounds.Height;
int numRectangles = (height - (GRIP_PADDING * 2)) / 4;
if (numRectangles > 0)
{
numRectangles++;
// a MenuStrip starts its grip lower and has fewer grip rectangles.
int yOffset = (toolStrip is MenuStrip) ? 2 : 0;
Rectangle[] shadowRects = new Rectangle[numRectangles];
int startY = GRIP_PADDING + 1 + yOffset;
int startX = (width / 2);
for (int i = 0; i < numRectangles; i++)
{
shadowRects[i] = (toolStrip.Orientation == Orientation.Horizontal) ?
new Rectangle(startX, startY, 1, 1) :
new Rectangle(startY, startX, 1, 1);
startY += 4;
}
// in RTL the GripLight rects should paint to the left of the GripDark rects.
int xOffset = (rightToLeft) ? 2 : -2;
if (rightToLeft)
{
// scoot over the rects in RTL so they fit within the bounds.
for (int i = 0; i < numRectangles; i++)
{
shadowRects[i].Offset(-xOffset, 0);
}
}
Brush b = _gripBrush;
for (int i = 0; i < numRectangles - 1; i++)
{
g.FillRectangle(b, shadowRects[i]);
}
for (int i = 0; i < numRectangles; i++)
{
shadowRects[i].Offset(xOffset, -2);
}
g.FillRectangles(b, shadowRects);
for (int i = 0; i < numRectangles; i++)
{
shadowRects[i].Offset(-2 * xOffset, 0);
}
g.FillRectangles(b, shadowRects);
}
}
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
{
ToolStripButton button = e.Item as ToolStripButton;
if (button != null && button.Enabled)
{
if (button.Selected || button.Checked)
{
// Rect of item's content area.
Rectangle contentRect = new Rectangle(0, 0, button.Width - 1, button.Height - 1);
Color pen;
Color brushBegin;
Color brushMiddle;
Color brushEnd;
if (button.Checked)
{
if (button.Selected)
{
pen = _table.ButtonCheckedHoveredBorder;
brushBegin = _table.ButtonCheckedHoveredBackground;
brushMiddle = _table.ButtonCheckedHoveredBackground;
brushEnd = _table.ButtonCheckedHoveredBackground;
}
else
{
pen = _table.ButtonCheckedBorder;
brushBegin = ColorTable.ButtonCheckedGradientBegin;
brushMiddle = ColorTable.ButtonCheckedGradientMiddle;
brushEnd = ColorTable.ButtonCheckedGradientEnd;
}
}
else if (button.Pressed)
{
pen = ColorTable.ButtonPressedBorder;
brushBegin = ColorTable.ButtonPressedGradientBegin;
brushMiddle = ColorTable.ButtonPressedGradientMiddle;
brushEnd = ColorTable.ButtonPressedGradientEnd;
}
else
{
pen = ColorTable.ButtonSelectedBorder;
brushBegin = ColorTable.ButtonSelectedGradientBegin;
brushMiddle = ColorTable.ButtonSelectedGradientMiddle;
brushEnd = ColorTable.ButtonSelectedGradientEnd;
}
DrawRectangle(e.Graphics, contentRect,
brushBegin, brushMiddle, brushEnd, pen, false);
}
}
else
{
base.OnRenderButtonBackground(e);
}
}
protected override void Initialize(ToolStrip toolStrip)
{
base.Initialize(toolStrip);
// IMPORTANT: enlarge grip area so grip can be rendered fully.
toolStrip.GripMargin = new Padding(toolStrip.GripMargin.All + 1);
}
protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
var cache = _palette.CommandBarMenuPopupDefault.BackgroundTop;
// IMPORTANT: not 100% accurate as the color change should only happen when the overflow menu is hovered.
// here color change happens when the overflow menu is displayed.
if (e.Item.Pressed)
_palette.CommandBarMenuPopupDefault.BackgroundTop = _palette.CommandBarToolbarOverflowPressed.Background;
base.OnRenderOverflowButtonBackground(e);
if (e.Item.Pressed)
_palette.CommandBarMenuPopupDefault.BackgroundTop = cache;
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
e.ArrowColor = e.Item.Selected ? _palette.CommandBarMenuPopupHovered.Arrow : _palette.CommandBarMenuPopupDefault.Arrow;
base.OnRenderArrow(e);
}
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
{
////base.OnRenderItemCheck(e);
using (var imageAttr = new ImageAttributes())
{
Color foreColor = e.Item.Selected ? _palette.CommandBarMenuPopupHovered.Checkmark : _palette.CommandBarMenuPopupDefault.Checkmark;
Color backColor = e.Item.Selected ? _palette.CommandBarMenuPopupHovered.CheckmarkBackground : _palette.CommandBarMenuPopupDefault.CheckmarkBackground;
Color borderColor = _palette.CommandBarMenuPopupDefault.Border;
// Create a color map.
ColorMap[] colorMap = new ColorMap[1];
colorMap[0] = new ColorMap();
// old color determined from testing
colorMap[0].OldColor = Color.FromArgb(4, 2, 4);
colorMap[0].NewColor = foreColor;
imageAttr.SetRemapTable(colorMap);
using (var b = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(b, e.ImageRectangle);
}
e.Graphics.DrawImage(e.Image, e.ImageRectangle, 0, 0, e.Image.Width, e.Image.Height, GraphicsUnit.Pixel, imageAttr);
using (var p = new Pen(borderColor))
{
e.Graphics.DrawRectangle(p, e.ImageRectangle);
}
}
}
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
Rectangle r = e.Item.ContentRectangle;
if (e.Vertical)
{
using (var p = new Pen(_palette.CommandBarToolbarDefault.Separator))
{
e.Graphics.DrawLine(p, r.X, r.Y, r.X, r.Y + r.Height);
}
using (var p = new Pen(_palette.CommandBarToolbarDefault.SeparatorAccent))
{
e.Graphics.DrawLine(p, r.X + 1, r.Y, r.X + 1, r.Y + r.Height);
}
}
else
{
// if this is a menu, then account for the image column
int x1 = r.X;
int x2 = r.X + r.Width;
var menu = e.ToolStrip as ToolStripDropDownMenu;
if (menu != null)
{
x1 += menu.Padding.Left;
x2 -= menu.Padding.Right;
}
using (var p = new Pen(_palette.CommandBarToolbarDefault.Separator))
{
e.Graphics.DrawLine(p, x1, r.Y, x2, r.Y);
}
using (var p = new Pen(_palette.CommandBarToolbarDefault.SeparatorAccent))
{
e.Graphics.DrawLine(p, x1, r.Y + 1, x2, r.Y + 1);
}
}
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
Color color = Color.Black;
var toolStrip = e.ToolStrip;
if (toolStrip is StatusStrip)
{
if (e.Item.Selected)
{
color = _palette.MainWindowStatusBarDefault.HighlightText;
}
else
{
color = _palette.MainWindowStatusBarDefault.Text;
}
}
else if (toolStrip is MenuStrip)
{
var button = e.Item as ToolStripButton;
var checkedButton = button != null && button.Checked;
if (!e.Item.Enabled)
{
color = _palette.CommandBarMenuPopupDisabled.Text;
}
else if (button != null && button.Pressed)
{
color = _palette.CommandBarToolbarButtonPressed.Text;
}
else if (e.Item.Selected && checkedButton)
{
color = _palette.CommandBarToolbarButtonCheckedHovered.Text;
}
else if (e.Item.Selected)
{
color = _palette.CommandBarMenuTopLevelHeaderHovered.Text;
}
else if (checkedButton)
{
color = _palette.CommandBarToolbarButtonChecked.Text;
}
else
{
color = _palette.CommandBarMenuDefault.Text;
}
}
else if (toolStrip is ToolStripDropDown)
{
// This might differ from above branch, but left the same here.
var button = e.Item as ToolStripButton;
var checkedButton = button != null && button.Checked;
if (!e.Item.Enabled)
{
color = _palette.CommandBarMenuPopupDisabled.Text;
}
else if (button != null && button.Pressed)
{
color = _palette.CommandBarToolbarButtonPressed.Text;
}
else if (e.Item.Selected && checkedButton)
{
color = _palette.CommandBarToolbarButtonCheckedHovered.Text;
}
else if (e.Item.Selected)
{
color = _palette.CommandBarMenuTopLevelHeaderHovered.Text;
}
else if (checkedButton)
{
color = _palette.CommandBarToolbarButtonChecked.Text;
}
else
{
color = _palette.CommandBarMenuDefault.Text;
}
}
else
{
// Default color, if not it will be black no matter what
if (!e.Item.Enabled)
{
color = _palette.CommandBarMenuPopupDisabled.Text;
}
else
{
color = _palette.CommandBarMenuDefault.Text;
}
}
TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, e.TextRectangle, color, e.TextFormat);
}
#region helpers
private static void DrawRectangle(Graphics graphics, Rectangle rect, Color brushBegin,
Color brushMiddle, Color brushEnd, Color penColor, bool glass)
{
RectangleF firstHalf = new RectangleF(
rect.X, rect.Y,
rect.Width, (float)rect.Height / 2);
RectangleF secondHalf = new RectangleF(
rect.X, rect.Y + (float)rect.Height / 2,
rect.Width, (float)rect.Height / 2);
if (brushMiddle.IsEmpty && brushEnd.IsEmpty)
{
graphics.FillRectangle(new SolidBrush(brushBegin), rect);
}
if (brushMiddle.IsEmpty)
{
rect.SafelyDrawLinearGradient(brushBegin, brushEnd, LinearGradientMode.Vertical, graphics);
}
else
{
firstHalf.SafelyDrawLinearGradientF(brushBegin, brushMiddle, LinearGradientMode.Vertical, graphics);
secondHalf.SafelyDrawLinearGradientF(brushMiddle, brushEnd, LinearGradientMode.Vertical, graphics);
}
if (glass)
{
Brush glassBrush = new SolidBrush(Color.FromArgb(120, Color.White));
graphics.FillRectangle(glassBrush, firstHalf);
}
if (penColor.A > 0)
{
graphics.DrawRectangle(new Pen(penColor), rect);
}
}
private static void DrawRectangle(Graphics graphics, Rectangle rect, Color brushBegin,
Color brushEnd, Color penColor, bool glass)
{
DrawRectangle(graphics, rect, brushBegin, Color.Empty, brushEnd, penColor, glass);
}
private static void DrawRectangle(Graphics graphics, Rectangle rect, Color brush,
Color penColor, bool glass)
{
DrawRectangle(graphics, rect, brush, Color.Empty, Color.Empty, penColor, glass);
}
private static void FillRoundRectangle(Graphics graphics, Brush brush, Rectangle rect, int radius)
{
float fx = Convert.ToSingle(rect.X);
float fy = Convert.ToSingle(rect.Y);
float fwidth = Convert.ToSingle(rect.Width);
float fheight = Convert.ToSingle(rect.Height);
float fradius = Convert.ToSingle(radius);
FillRoundRectangle(graphics, brush, fx, fy, fwidth, fheight, fradius);
}
private static void FillRoundRectangle(Graphics graphics, Brush brush, float x, float y, float width, float height, float radius)
{
RectangleF rectangle = new RectangleF(x, y, width, height);
GraphicsPath path = GetRoundedRect(rectangle, radius);
graphics.FillPath(brush, path);
}
private static void DrawRoundRectangle(Graphics graphics, Pen pen, Rectangle rect, int radius)
{
float fx = Convert.ToSingle(rect.X);
float fy = Convert.ToSingle(rect.Y);
float fwidth = Convert.ToSingle(rect.Width);
float fheight = Convert.ToSingle(rect.Height);
float fradius = Convert.ToSingle(radius);
DrawRoundRectangle(graphics, pen, fx, fy, fwidth, fheight, fradius);
}
private static void DrawRoundRectangle(Graphics graphics, Pen pen, float x, float y, float width, float height, float radius)
{
RectangleF rectangle = new RectangleF(x, y, width, height);
GraphicsPath path = GetRoundedRect(rectangle, radius);
graphics.DrawPath(pen, path);
}
private static GraphicsPath GetRoundedRect(RectangleF baseRect, float radius)
{
// if corner radius is less than or equal to zero,
// return the original rectangle
if (radius <= 0)
{
GraphicsPath mPath = new GraphicsPath();
mPath.AddRectangle(baseRect);
mPath.CloseFigure();
return mPath;
}
// if the corner radius is greater than or equal to
// half the width, or height (whichever is shorter)
// then return a capsule instead of a lozenge
if (radius >= (Math.Min(baseRect.Width, baseRect.Height)) / 2.0)
return GetCapsule(baseRect);
// create the arc for the rectangle sides and declare
// a graphics path object for the drawing
float diameter = radius * 2.0F;
SizeF sizeF = new SizeF(diameter, diameter);
RectangleF arc = new RectangleF(baseRect.Location, sizeF);
GraphicsPath path = new GraphicsPath();
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = baseRect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
private static GraphicsPath GetCapsule(RectangleF baseRect)
{
RectangleF arc;
GraphicsPath path = new GraphicsPath();
try
{
float diameter;
if (baseRect.Width > baseRect.Height)
{
// return horizontal capsule
diameter = baseRect.Height;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF(baseRect.Location, sizeF);
path.AddArc(arc, 90, 180);
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 180);
}
else if (baseRect.Width < baseRect.Height)
{
// return vertical capsule
diameter = baseRect.Width;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF(baseRect.Location, sizeF);
path.AddArc(arc, 180, 180);
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 180);
}
else
{
// return circle
path.AddEllipse(baseRect);
}
}
catch
{
path.AddEllipse(baseRect);
}
finally
{
path.CloseFigure();
}
return path;
}
#endregion
// */
#endregion
}
}
| |
// dnlib: See LICENSE.txt for more info
using System.Collections.Generic;
#pragma warning disable 1591 // XML doc comments
namespace dnlib.DotNet.MD {
/// <summary>
/// Equality comparer for all raw rows
/// </summary>
public sealed class RawRowEqualityComparer : IEqualityComparer<RawModuleRow>,
IEqualityComparer<RawTypeRefRow>, IEqualityComparer<RawTypeDefRow>,
IEqualityComparer<RawFieldPtrRow>, IEqualityComparer<RawFieldRow>,
IEqualityComparer<RawMethodPtrRow>, IEqualityComparer<RawMethodRow>,
IEqualityComparer<RawParamPtrRow>, IEqualityComparer<RawParamRow>,
IEqualityComparer<RawInterfaceImplRow>, IEqualityComparer<RawMemberRefRow>,
IEqualityComparer<RawConstantRow>, IEqualityComparer<RawCustomAttributeRow>,
IEqualityComparer<RawFieldMarshalRow>, IEqualityComparer<RawDeclSecurityRow>,
IEqualityComparer<RawClassLayoutRow>, IEqualityComparer<RawFieldLayoutRow>,
IEqualityComparer<RawStandAloneSigRow>, IEqualityComparer<RawEventMapRow>,
IEqualityComparer<RawEventPtrRow>, IEqualityComparer<RawEventRow>,
IEqualityComparer<RawPropertyMapRow>, IEqualityComparer<RawPropertyPtrRow>,
IEqualityComparer<RawPropertyRow>, IEqualityComparer<RawMethodSemanticsRow>,
IEqualityComparer<RawMethodImplRow>, IEqualityComparer<RawModuleRefRow>,
IEqualityComparer<RawTypeSpecRow>, IEqualityComparer<RawImplMapRow>,
IEqualityComparer<RawFieldRVARow>, IEqualityComparer<RawENCLogRow>,
IEqualityComparer<RawENCMapRow>, IEqualityComparer<RawAssemblyRow>,
IEqualityComparer<RawAssemblyProcessorRow>, IEqualityComparer<RawAssemblyOSRow>,
IEqualityComparer<RawAssemblyRefRow>, IEqualityComparer<RawAssemblyRefProcessorRow>,
IEqualityComparer<RawAssemblyRefOSRow>, IEqualityComparer<RawFileRow>,
IEqualityComparer<RawExportedTypeRow>, IEqualityComparer<RawManifestResourceRow>,
IEqualityComparer<RawNestedClassRow>, IEqualityComparer<RawGenericParamRow>,
IEqualityComparer<RawMethodSpecRow>, IEqualityComparer<RawGenericParamConstraintRow>,
IEqualityComparer<RawDocumentRow>, IEqualityComparer<RawMethodDebugInformationRow>,
IEqualityComparer<RawLocalScopeRow>, IEqualityComparer<RawLocalVariableRow>,
IEqualityComparer<RawLocalConstantRow>, IEqualityComparer<RawImportScopeRow>,
IEqualityComparer<RawStateMachineMethodRow>, IEqualityComparer<RawCustomDebugInformationRow> {
/// <summary>
/// Default instance
/// </summary>
public static readonly RawRowEqualityComparer Instance = new RawRowEqualityComparer();
static int rol(uint val, int shift) => (int)((val << shift) | (val >> (32 - shift)));
public bool Equals(RawModuleRow x, RawModuleRow y) =>
x.Generation == y.Generation &&
x.Name == y.Name &&
x.Mvid == y.Mvid &&
x.EncId == y.EncId &&
x.EncBaseId == y.EncBaseId;
public int GetHashCode(RawModuleRow obj) =>
obj.Generation +
rol(obj.Name, 3) +
rol(obj.Mvid, 7) +
rol(obj.EncId, 11) +
rol(obj.EncBaseId, 15);
public bool Equals(RawTypeRefRow x, RawTypeRefRow y) =>
x.ResolutionScope == y.ResolutionScope &&
x.Name == y.Name &&
x.Namespace == y.Namespace;
public int GetHashCode(RawTypeRefRow obj) =>
(int)obj.ResolutionScope +
rol(obj.Name, 3) +
rol(obj.Namespace, 7);
public bool Equals(RawTypeDefRow x, RawTypeDefRow y) =>
x.Flags == y.Flags &&
x.Name == y.Name &&
x.Namespace == y.Namespace &&
x.Extends == y.Extends &&
x.FieldList == y.FieldList &&
x.MethodList == y.MethodList;
public int GetHashCode(RawTypeDefRow obj) =>
(int)obj.Flags +
rol(obj.Name, 3) +
rol(obj.Namespace, 7) +
rol(obj.Extends, 11) +
rol(obj.FieldList, 15) +
rol(obj.MethodList, 19);
public bool Equals(RawFieldPtrRow x, RawFieldPtrRow y) => x.Field == y.Field;
public int GetHashCode(RawFieldPtrRow obj) => (int)obj.Field;
public bool Equals(RawFieldRow x, RawFieldRow y) =>
x.Flags == y.Flags &&
x.Name == y.Name &&
x.Signature == y.Signature;
public int GetHashCode(RawFieldRow obj) =>
(int)obj.Flags +
rol(obj.Name, 3) +
rol(obj.Signature, 7);
public bool Equals(RawMethodPtrRow x, RawMethodPtrRow y) => x.Method == y.Method;
public int GetHashCode(RawMethodPtrRow obj) => (int)obj.Method;
public bool Equals(RawMethodRow x, RawMethodRow y) =>
x.RVA == y.RVA &&
x.ImplFlags == y.ImplFlags &&
x.Flags == y.Flags &&
x.Name == y.Name &&
x.Signature == y.Signature &&
x.ParamList == y.ParamList;
public int GetHashCode(RawMethodRow obj) =>
(int)obj.RVA +
rol(obj.ImplFlags, 3) +
rol(obj.Flags, 7) +
rol(obj.Name, 11) +
rol(obj.Signature, 15) +
rol(obj.ParamList, 19);
public bool Equals(RawParamPtrRow x, RawParamPtrRow y) => x.Param == y.Param;
public int GetHashCode(RawParamPtrRow obj) => (int)obj.Param;
public bool Equals(RawParamRow x, RawParamRow y) =>
x.Flags == y.Flags &&
x.Sequence == y.Sequence &&
x.Name == y.Name;
public int GetHashCode(RawParamRow obj) =>
(int)obj.Flags +
rol(obj.Sequence, 3) +
rol(obj.Name, 7);
public bool Equals(RawInterfaceImplRow x, RawInterfaceImplRow y) =>
x.Class == y.Class &&
x.Interface == y.Interface;
public int GetHashCode(RawInterfaceImplRow obj) =>
(int)obj.Class +
rol(obj.Interface, 3);
public bool Equals(RawMemberRefRow x, RawMemberRefRow y) =>
x.Class == y.Class &&
x.Name == y.Name &&
x.Signature == y.Signature;
public int GetHashCode(RawMemberRefRow obj) =>
(int)obj.Class +
rol(obj.Name, 3) +
rol(obj.Signature, 7);
public bool Equals(RawConstantRow x, RawConstantRow y) =>
x.Type == y.Type &&
x.Padding == y.Padding &&
x.Parent == y.Parent &&
x.Value == y.Value;
public int GetHashCode(RawConstantRow obj) =>
(int)obj.Type +
rol(obj.Padding, 3) +
rol(obj.Parent, 7) +
rol(obj.Value, 11);
public bool Equals(RawCustomAttributeRow x, RawCustomAttributeRow y) =>
x.Parent == y.Parent &&
x.Type == y.Type &&
x.Value == y.Value;
public int GetHashCode(RawCustomAttributeRow obj) =>
(int)obj.Parent +
rol(obj.Type, 3) +
rol(obj.Value, 7);
public bool Equals(RawFieldMarshalRow x, RawFieldMarshalRow y) =>
x.Parent == y.Parent &&
x.NativeType == y.NativeType;
public int GetHashCode(RawFieldMarshalRow obj) =>
(int)obj.Parent +
rol(obj.NativeType, 3);
public bool Equals(RawDeclSecurityRow x, RawDeclSecurityRow y) =>
x.Action == y.Action &&
x.Parent == y.Parent &&
x.PermissionSet == y.PermissionSet;
public int GetHashCode(RawDeclSecurityRow obj) =>
(int)obj.Action +
rol(obj.Parent, 3) +
rol(obj.PermissionSet, 7);
public bool Equals(RawClassLayoutRow x, RawClassLayoutRow y) =>
x.PackingSize == y.PackingSize &&
x.ClassSize == y.ClassSize &&
x.Parent == y.Parent;
public int GetHashCode(RawClassLayoutRow obj) =>
(int)obj.PackingSize +
rol(obj.ClassSize, 3) +
rol(obj.Parent, 7);
public bool Equals(RawFieldLayoutRow x, RawFieldLayoutRow y) =>
x.OffSet == y.OffSet &&
x.Field == y.Field;
public int GetHashCode(RawFieldLayoutRow obj) =>
(int)obj.OffSet +
rol(obj.Field, 3);
public bool Equals(RawStandAloneSigRow x, RawStandAloneSigRow y) => x.Signature == y.Signature;
public int GetHashCode(RawStandAloneSigRow obj) => (int)obj.Signature;
public bool Equals(RawEventMapRow x, RawEventMapRow y) =>
x.Parent == y.Parent &&
x.EventList == y.EventList;
public int GetHashCode(RawEventMapRow obj) =>
(int)obj.Parent +
rol(obj.EventList, 3);
public bool Equals(RawEventPtrRow x, RawEventPtrRow y) => x.Event == y.Event;
public int GetHashCode(RawEventPtrRow obj) => (int)obj.Event;
public bool Equals(RawEventRow x, RawEventRow y) =>
x.EventFlags == y.EventFlags &&
x.Name == y.Name &&
x.EventType == y.EventType;
public int GetHashCode(RawEventRow obj) =>
(int)obj.EventFlags +
rol(obj.Name, 3) +
rol(obj.EventType, 7);
public bool Equals(RawPropertyMapRow x, RawPropertyMapRow y) =>
x.Parent == y.Parent &&
x.PropertyList == y.PropertyList;
public int GetHashCode(RawPropertyMapRow obj) =>
(int)obj.Parent +
rol(obj.PropertyList, 3);
public bool Equals(RawPropertyPtrRow x, RawPropertyPtrRow y) => x.Property == y.Property;
public int GetHashCode(RawPropertyPtrRow obj) => (int)obj.Property;
public bool Equals(RawPropertyRow x, RawPropertyRow y) =>
x.PropFlags == y.PropFlags &&
x.Name == y.Name &&
x.Type == y.Type;
public int GetHashCode(RawPropertyRow obj) =>
(int)obj.PropFlags +
rol(obj.Name, 3) +
rol(obj.Type, 7);
public bool Equals(RawMethodSemanticsRow x, RawMethodSemanticsRow y) =>
x.Semantic == y.Semantic &&
x.Method == y.Method &&
x.Association == y.Association;
public int GetHashCode(RawMethodSemanticsRow obj) =>
(int)obj.Semantic +
rol(obj.Method, 3) +
rol(obj.Association, 7);
public bool Equals(RawMethodImplRow x, RawMethodImplRow y) =>
x.Class == y.Class &&
x.MethodBody == y.MethodBody &&
x.MethodDeclaration == y.MethodDeclaration;
public int GetHashCode(RawMethodImplRow obj) =>
(int)obj.Class +
rol(obj.MethodBody, 3) +
rol(obj.MethodDeclaration, 7);
public bool Equals(RawModuleRefRow x, RawModuleRefRow y) => x.Name == y.Name;
public int GetHashCode(RawModuleRefRow obj) => (int)obj.Name;
public bool Equals(RawTypeSpecRow x, RawTypeSpecRow y) => x.Signature == y.Signature;
public int GetHashCode(RawTypeSpecRow obj) => (int)obj.Signature;
public bool Equals(RawImplMapRow x, RawImplMapRow y) =>
x.MappingFlags == y.MappingFlags &&
x.MemberForwarded == y.MemberForwarded &&
x.ImportName == y.ImportName &&
x.ImportScope == y.ImportScope;
public int GetHashCode(RawImplMapRow obj) =>
(int)obj.MappingFlags +
rol(obj.MemberForwarded, 3) +
rol(obj.ImportName, 7) +
rol(obj.ImportScope, 11);
public bool Equals(RawFieldRVARow x, RawFieldRVARow y) =>
x.RVA == y.RVA &&
x.Field == y.Field;
public int GetHashCode(RawFieldRVARow obj) =>
(int)obj.RVA +
rol(obj.Field, 3);
public bool Equals(RawENCLogRow x, RawENCLogRow y) =>
x.Token == y.Token &&
x.FuncCode == y.FuncCode;
public int GetHashCode(RawENCLogRow obj) =>
(int)obj.Token +
rol(obj.FuncCode, 3);
public bool Equals(RawENCMapRow x, RawENCMapRow y) => x.Token == y.Token;
public int GetHashCode(RawENCMapRow obj) => (int)obj.Token;
public bool Equals(RawAssemblyRow x, RawAssemblyRow y) =>
x.HashAlgId == y.HashAlgId &&
x.MajorVersion == y.MajorVersion &&
x.MinorVersion == y.MinorVersion &&
x.BuildNumber == y.BuildNumber &&
x.RevisionNumber == y.RevisionNumber &&
x.Flags == y.Flags &&
x.PublicKey == y.PublicKey &&
x.Name == y.Name &&
x.Locale == y.Locale;
public int GetHashCode(RawAssemblyRow obj) =>
(int)obj.HashAlgId +
rol(obj.MajorVersion, 3) +
rol(obj.MinorVersion, 7) +
rol(obj.BuildNumber, 11) +
rol(obj.RevisionNumber, 15) +
rol(obj.Flags, 19) +
rol(obj.PublicKey, 23) +
rol(obj.Name, 27) +
rol(obj.Locale, 31);
public bool Equals(RawAssemblyProcessorRow x, RawAssemblyProcessorRow y) => x.Processor == y.Processor;
public int GetHashCode(RawAssemblyProcessorRow obj) => (int)obj.Processor;
public bool Equals(RawAssemblyOSRow x, RawAssemblyOSRow y) =>
x.OSPlatformId == y.OSPlatformId &&
x.OSMajorVersion == y.OSMajorVersion &&
x.OSMinorVersion == y.OSMinorVersion;
public int GetHashCode(RawAssemblyOSRow obj) =>
(int)obj.OSPlatformId +
rol(obj.OSMajorVersion, 3) +
rol(obj.OSMinorVersion, 7);
public bool Equals(RawAssemblyRefRow x, RawAssemblyRefRow y) =>
x.MajorVersion == y.MajorVersion &&
x.MinorVersion == y.MinorVersion &&
x.BuildNumber == y.BuildNumber &&
x.RevisionNumber == y.RevisionNumber &&
x.Flags == y.Flags &&
x.PublicKeyOrToken == y.PublicKeyOrToken &&
x.Name == y.Name &&
x.Locale == y.Locale &&
x.HashValue == y.HashValue;
public int GetHashCode(RawAssemblyRefRow obj) =>
(int)obj.MajorVersion +
rol(obj.MinorVersion, 3) +
rol(obj.BuildNumber, 7) +
rol(obj.RevisionNumber, 11) +
rol(obj.Flags, 15) +
rol(obj.PublicKeyOrToken, 19) +
rol(obj.Name, 23) +
rol(obj.Locale, 27) +
rol(obj.HashValue, 31);
public bool Equals(RawAssemblyRefProcessorRow x, RawAssemblyRefProcessorRow y) =>
x.Processor == y.Processor &&
x.AssemblyRef == y.AssemblyRef;
public int GetHashCode(RawAssemblyRefProcessorRow obj) =>
(int)obj.Processor +
rol(obj.AssemblyRef, 3);
public bool Equals(RawAssemblyRefOSRow x, RawAssemblyRefOSRow y) =>
x.OSPlatformId == y.OSPlatformId &&
x.OSMajorVersion == y.OSMajorVersion &&
x.OSMinorVersion == y.OSMinorVersion &&
x.AssemblyRef == y.AssemblyRef;
public int GetHashCode(RawAssemblyRefOSRow obj) =>
(int)obj.OSPlatformId +
rol(obj.OSMajorVersion, 3) +
rol(obj.OSMinorVersion, 7) +
rol(obj.AssemblyRef, 11);
public bool Equals(RawFileRow x, RawFileRow y) =>
x.Flags == y.Flags &&
x.Name == y.Name &&
x.HashValue == y.HashValue;
public int GetHashCode(RawFileRow obj) =>
(int)obj.Flags +
rol(obj.Name, 3) +
rol(obj.HashValue, 7);
public bool Equals(RawExportedTypeRow x, RawExportedTypeRow y) =>
x.Flags == y.Flags &&
x.TypeDefId == y.TypeDefId &&
x.TypeName == y.TypeName &&
x.TypeNamespace == y.TypeNamespace &&
x.Implementation == y.Implementation;
public int GetHashCode(RawExportedTypeRow obj) =>
(int)obj.Flags +
rol(obj.TypeDefId, 3) +
rol(obj.TypeName, 7) +
rol(obj.TypeNamespace, 11) +
rol(obj.Implementation, 15);
public bool Equals(RawManifestResourceRow x, RawManifestResourceRow y) =>
x.Offset == y.Offset &&
x.Flags == y.Flags &&
x.Name == y.Name &&
x.Implementation == y.Implementation;
public int GetHashCode(RawManifestResourceRow obj) =>
(int)obj.Offset +
rol(obj.Flags, 3) +
rol(obj.Name, 7) +
rol(obj.Implementation, 11);
public bool Equals(RawNestedClassRow x, RawNestedClassRow y) =>
x.NestedClass == y.NestedClass &&
x.EnclosingClass == y.EnclosingClass;
public int GetHashCode(RawNestedClassRow obj) =>
(int)obj.NestedClass +
rol(obj.EnclosingClass, 3);
public bool Equals(RawGenericParamRow x, RawGenericParamRow y) =>
x.Number == y.Number &&
x.Flags == y.Flags &&
x.Owner == y.Owner &&
x.Name == y.Name &&
x.Kind == y.Kind;
public int GetHashCode(RawGenericParamRow obj) =>
(int)obj.Number +
rol(obj.Flags, 3) +
rol(obj.Owner, 7) +
rol(obj.Name, 11) +
rol(obj.Kind, 15);
public bool Equals(RawMethodSpecRow x, RawMethodSpecRow y) =>
x.Method == y.Method &&
x.Instantiation == y.Instantiation;
public int GetHashCode(RawMethodSpecRow obj) =>
(int)obj.Method +
rol(obj.Instantiation, 3);
public bool Equals(RawGenericParamConstraintRow x, RawGenericParamConstraintRow y) =>
x.Owner == y.Owner &&
x.Constraint == y.Constraint;
public int GetHashCode(RawGenericParamConstraintRow obj) =>
(int)obj.Owner +
rol(obj.Constraint, 3);
public bool Equals(RawDocumentRow x, RawDocumentRow y) =>
x.Name == y.Name &&
x.HashAlgorithm == y.HashAlgorithm &&
x.Hash == y.Hash &&
x.Language == y.Language;
public int GetHashCode(RawDocumentRow obj) =>
(int)obj.Name +
rol(obj.HashAlgorithm, 3) +
rol(obj.Hash, 7) +
rol(obj.Language, 11);
public bool Equals(RawMethodDebugInformationRow x, RawMethodDebugInformationRow y) =>
x.Document == y.Document &&
x.SequencePoints == y.SequencePoints;
public int GetHashCode(RawMethodDebugInformationRow obj) =>
(int)obj.Document +
rol(obj.SequencePoints, 3);
public bool Equals(RawLocalScopeRow x, RawLocalScopeRow y) =>
x.Method == y.Method &&
x.ImportScope == y.ImportScope &&
x.VariableList == y.VariableList &&
x.ConstantList == y.ConstantList &&
x.StartOffset == y.StartOffset &&
x.Length == y.Length;
public int GetHashCode(RawLocalScopeRow obj) =>
(int)obj.Method +
rol(obj.ImportScope, 3) +
rol(obj.VariableList, 7) +
rol(obj.ConstantList, 11) +
rol(obj.StartOffset, 15) +
rol(obj.Length, 19);
public bool Equals(RawLocalVariableRow x, RawLocalVariableRow y) =>
x.Attributes == y.Attributes &&
x.Index == y.Index &&
x.Name == y.Name;
public int GetHashCode(RawLocalVariableRow obj) =>
obj.Attributes +
rol(obj.Index, 3) +
rol(obj.Name, 7);
public bool Equals(RawLocalConstantRow x, RawLocalConstantRow y) =>
x.Name == y.Name &&
x.Signature == y.Signature;
public int GetHashCode(RawLocalConstantRow obj) =>
(int)obj.Name +
rol(obj.Signature, 3);
public bool Equals(RawImportScopeRow x, RawImportScopeRow y) =>
x.Parent == y.Parent &&
x.Imports == y.Imports;
public int GetHashCode(RawImportScopeRow obj) =>
(int)obj.Parent +
rol(obj.Imports, 3);
public bool Equals(RawStateMachineMethodRow x, RawStateMachineMethodRow y) =>
x.MoveNextMethod == y.MoveNextMethod &&
x.KickoffMethod == y.KickoffMethod;
public int GetHashCode(RawStateMachineMethodRow obj) =>
(int)obj.MoveNextMethod +
rol(obj.KickoffMethod, 3);
public bool Equals(RawCustomDebugInformationRow x, RawCustomDebugInformationRow y) =>
x.Parent == y.Parent &&
x.Kind == y.Kind &&
x.Value == y.Value;
public int GetHashCode(RawCustomDebugInformationRow obj) =>
(int)obj.Parent +
rol(obj.Kind, 3) +
rol(obj.Value, 7);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with block resources.
///
/// A block object is a simple rule, when matched, pushes a newly created
/// mandate to a blocked state. These details can be an exact match, like a
/// bank account
/// or an email, or a more generic match such as an email domain. New block
/// types may be added
/// over time. Payments and subscriptions can't be created against mandates
/// in blocked state.
///
/// <p class="notice">
/// Client libraries have not yet been updated for this API but will be
/// released soon.
/// This API is currently only available for approved integrators - please
/// <a href="mailto:[email protected]">get in touch</a> if you would like
/// to use this API.
/// </p>
/// </summary>
public class BlockService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public BlockService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Creates a new Block of a given type. By default it will be active.
/// </summary>
/// <param name="request">An optional `BlockCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single block resource</returns>
public Task<BlockResponse> CreateAsync(BlockCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<BlockResponse>("POST", "/blocks", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "blocks", customiseRequestMessage);
}
/// <summary>
/// Retrieves the details of an existing block.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BLC".</param>
/// <param name="request">An optional `BlockGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single block resource</returns>
public Task<BlockResponse> GetAsync(string identity, BlockGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<BlockResponse>("GET", "/blocks/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of
/// your blocks.
/// </summary>
/// <param name="request">An optional `BlockListRequest` representing the query parameters for this list request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A set of block resources</returns>
public Task<BlockListResponse> ListAsync(BlockListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockListRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<BlockListResponse>("GET", "/blocks", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Get a lazily enumerated list of blocks.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<Block> All(BlockListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockListRequest();
string cursor = null;
do
{
request.After = cursor;
var result = Task.Run(() => ListAsync(request, customiseRequestMessage)).Result;
foreach (var item in result.Blocks)
{
yield return item;
}
cursor = result.Meta?.Cursors?.After;
} while (cursor != null);
}
/// <summary>
/// Get a lazily enumerated list of blocks.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<Task<IReadOnlyList<Block>>> AllAsync(BlockListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockListRequest();
return new TaskEnumerable<IReadOnlyList<Block>, string>(async after =>
{
request.After = after;
var list = await this.ListAsync(request, customiseRequestMessage);
return Tuple.Create(list.Blocks, list.Meta?.Cursors?.After);
});
}
/// <summary>
/// Disables a block so that it no longer will prevent mandate creation.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BLC".</param>
/// <param name="request">An optional `BlockDisableRequest` representing the body for this disable request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single block resource</returns>
public Task<BlockResponse> DisableAsync(string identity, BlockDisableRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockDisableRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<BlockResponse>("POST", "/blocks/:identity/actions/disable", urlParams, request, null, "data", customiseRequestMessage);
}
/// <summary>
/// Enables a previously disabled block so that it will prevent mandate
/// creation
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BLC".</param>
/// <param name="request">An optional `BlockEnableRequest` representing the body for this enable request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single block resource</returns>
public Task<BlockResponse> EnableAsync(string identity, BlockEnableRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockEnableRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<BlockResponse>("POST", "/blocks/:identity/actions/enable", urlParams, request, null, "data", customiseRequestMessage);
}
/// <summary>
/// Creates new blocks for a given reference. By default blocks will be
/// active.
/// Returns 201 if at least one block was created. Returns 200 if there
/// were no new
/// blocks created.
/// </summary>
/// <param name="request">An optional `BlockBlockByRefRequest` representing the body for this block_by_ref request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A set of block resources</returns>
public Task<BlockListResponse> BlockByRefAsync(BlockBlockByRefRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new BlockBlockByRefRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<BlockListResponse>("POST", "/block_by_ref", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Creates a new Block of a given type. By default it will be active.
/// </summary>
public class BlockCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// Shows if the block is active or disabled. Only active blocks will be
/// used when deciding
/// if a mandate should be blocked.
/// </summary>
[JsonProperty("active")]
public bool? Active { get; set; }
/// <summary>
/// Type of entity we will seek to match against when blocking the
/// mandate. This
/// can currently be one of 'email', 'email_domain', or 'bank_account'.
/// </summary>
[JsonProperty("block_type")]
public string BlockType { get; set; }
/// <summary>
/// Type of entity we will seek to match against when blocking the
/// mandate. This
/// can currently be one of 'email', 'email_domain', or 'bank_account'.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockBlockType
{
/// <summary>`block_type` with a value of "email"</summary>
[EnumMember(Value = "email")]
Email,
/// <summary>`block_type` with a value of "email_domain"</summary>
[EnumMember(Value = "email_domain")]
EmailDomain,
/// <summary>`block_type` with a value of "bank_account"</summary>
[EnumMember(Value = "bank_account")]
BankAccount,
}
/// <summary>
/// This field is required if the reason_type is other. It should be a
/// description of
/// the reason for why you wish to block this payer and why it does not
/// align with the
/// given reason_types. This is intended to help us improve our
/// knowledge of types of
/// fraud.
/// </summary>
[JsonProperty("reason_description")]
public string ReasonDescription { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonProperty("reason_type")]
public string ReasonType { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockReasonType
{
/// <summary>`reason_type` with a value of "identity_fraud"</summary>
[EnumMember(Value = "identity_fraud")]
IdentityFraud,
/// <summary>`reason_type` with a value of "no_intent_to_pay"</summary>
[EnumMember(Value = "no_intent_to_pay")]
NoIntentToPay,
/// <summary>`reason_type` with a value of "unfair_chargeback"</summary>
[EnumMember(Value = "unfair_chargeback")]
UnfairChargeback,
/// <summary>`reason_type` with a value of "other"</summary>
[EnumMember(Value = "other")]
Other,
}
/// <summary>
/// This field is a reference to the value you wish to block. This may
/// be the raw value
/// (in the case of emails or email domains) or the ID of the resource
/// (in the case of
/// bank accounts). This means in order to block a specific bank account
/// it must already
/// have been created as a resource.
/// </summary>
[JsonProperty("resource_reference")]
public string ResourceReference { get; set; }
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Retrieves the details of an existing block.
/// </summary>
public class BlockGetRequest
{
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your
/// blocks.
/// </summary>
public class BlockListRequest
{
/// <summary>
/// Cursor pointing to the start of the desired set.
/// </summary>
[JsonProperty("after")]
public string After { get; set; }
/// <summary>
/// Cursor pointing to the end of the desired set.
/// </summary>
[JsonProperty("before")]
public string Before { get; set; }
/// <summary>
/// ID of a [Block](#core-endpoints-blocks).
/// </summary>
[JsonProperty("block")]
public string Block { get; set; }
/// <summary>
/// Type of entity we will seek to match against when blocking the
/// mandate. This
/// can currently be one of 'email', 'email_domain', or 'bank_account'.
/// </summary>
[JsonProperty("block_type")]
public string BlockType { get; set; }
/// <summary>
/// Type of entity we will seek to match against when blocking the
/// mandate. This
/// can currently be one of 'email', 'email_domain', or 'bank_account'.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockBlockType
{
/// <summary>`block_type` with a value of "email"</summary>
[EnumMember(Value = "email")]
Email,
/// <summary>`block_type` with a value of "email_domain"</summary>
[EnumMember(Value = "email_domain")]
EmailDomain,
/// <summary>`block_type` with a value of "bank_account"</summary>
[EnumMember(Value = "bank_account")]
BankAccount,
}
/// <summary>
/// Fixed [timestamp](#api-usage-time-zones--dates), recording when this
/// resource was created.
/// </summary>
[JsonProperty("created_at")]
public CreatedAtParam CreatedAt { get; set; }
/// <summary>
/// Specify filters to limit records by creation time.
/// </summary>
public class CreatedAtParam
{
/// <summary>
/// Limit to records created after the specified date-time.
/// </summary>
[JsonProperty("gt")]
public DateTimeOffset? GreaterThan { get; set; }
/// <summary>
/// Limit to records created on or after the specified date-time.
/// </summary>
[JsonProperty("gte")]
public DateTimeOffset? GreaterThanOrEqual { get; set; }
/// <summary>
/// Limit to records created before the specified date-time.
/// </summary>
[JsonProperty("lt")]
public DateTimeOffset? LessThan { get; set; }
/// <summary>
///Limit to records created on or before the specified date-time.
/// </summary>
[JsonProperty("lte")]
public DateTimeOffset? LessThanOrEqual { get; set; }
}
/// <summary>
/// Number of records to return.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonProperty("reason_type")]
public string ReasonType { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockReasonType
{
/// <summary>`reason_type` with a value of "identity_fraud"</summary>
[EnumMember(Value = "identity_fraud")]
IdentityFraud,
/// <summary>`reason_type` with a value of "no_intent_to_pay"</summary>
[EnumMember(Value = "no_intent_to_pay")]
NoIntentToPay,
/// <summary>`reason_type` with a value of "unfair_chargeback"</summary>
[EnumMember(Value = "unfair_chargeback")]
UnfairChargeback,
/// <summary>`reason_type` with a value of "other"</summary>
[EnumMember(Value = "other")]
Other,
}
/// <summary>
/// Fixed [timestamp](#api-usage-time-zones--dates), recording when this
/// resource was updated.
/// </summary>
[JsonProperty("updated_at")]
public string UpdatedAt { get; set; }
}
/// <summary>
/// Disables a block so that it no longer will prevent mandate creation.
/// </summary>
public class BlockDisableRequest
{
}
/// <summary>
/// Enables a previously disabled block so that it will prevent mandate
/// creation
/// </summary>
public class BlockEnableRequest
{
}
/// <summary>
/// Creates new blocks for a given reference. By default blocks will be
/// active.
/// Returns 201 if at least one block was created. Returns 200 if there were
/// no new
/// blocks created.
/// </summary>
public class BlockBlockByRefRequest
{
/// <summary>
/// Shows if the block is active or disabled. Only active blocks will be
/// used when deciding
/// if a mandate should be blocked.
/// </summary>
[JsonProperty("active")]
public bool? Active { get; set; }
/// <summary>
/// This field is required if the reason_type is other. It should be a
/// description of
/// the reason for why you wish to block this payer and why it does not
/// align with the
/// given reason_types. This is intended to help us improve our
/// knowledge of types of
/// fraud.
/// </summary>
[JsonProperty("reason_description")]
public string ReasonDescription { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonProperty("reason_type")]
public string ReasonType { get; set; }
/// <summary>
/// The reason you wish to block this payer, can currently be one of
/// 'identity_fraud',
/// 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't
/// captured by one of the
/// above then 'other' can be selected but you must provide a reason
/// description.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockReasonType
{
/// <summary>`reason_type` with a value of "identity_fraud"</summary>
[EnumMember(Value = "identity_fraud")]
IdentityFraud,
/// <summary>`reason_type` with a value of "no_intent_to_pay"</summary>
[EnumMember(Value = "no_intent_to_pay")]
NoIntentToPay,
/// <summary>`reason_type` with a value of "unfair_chargeback"</summary>
[EnumMember(Value = "unfair_chargeback")]
UnfairChargeback,
/// <summary>`reason_type` with a value of "other"</summary>
[EnumMember(Value = "other")]
Other,
}
/// <summary>
/// Type of entity we will seek to get the associated emails and bank
/// accounts to
/// create blocks from. This can currently be one of 'customer' or
/// 'mandate'.
/// </summary>
[JsonProperty("reference_type")]
public string ReferenceType { get; set; }
/// <summary>
/// Type of entity we will seek to get the associated emails and bank
/// accounts to
/// create blocks from. This can currently be one of 'customer' or
/// 'mandate'.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum BlockReferenceType
{
/// <summary>`reference_type` with a value of "customer"</summary>
[EnumMember(Value = "customer")]
Customer,
/// <summary>`reference_type` with a value of "mandate"</summary>
[EnumMember(Value = "mandate")]
Mandate,
}
/// <summary>
/// This field is a reference to the entity you wish to block based on
/// its emails
/// and bank accounts. This may be the ID of a customer or a mandate.
/// This means in
/// order to block by reference the entity must have already been
/// created as a
/// resource.
/// </summary>
[JsonProperty("reference_value")]
public string ReferenceValue { get; set; }
}
/// <summary>
/// An API response for a request returning a single block.
/// </summary>
public class BlockResponse : ApiResponse
{
/// <summary>
/// The block from the response.
/// </summary>
[JsonProperty("blocks")]
public Block Block { get; private set; }
}
/// <summary>
/// An API response for a request returning a list of blocks.
/// </summary>
public class BlockListResponse : ApiResponse
{
/// <summary>
/// The list of blocks from the response.
/// </summary>
[JsonProperty("blocks")]
public IReadOnlyList<Block> Blocks { get; private set; }
/// <summary>
/// Response metadata (e.g. pagination cursors)
/// </summary>
public Meta Meta { get; private set; }
}
}
| |
// CodeContracts
//
// 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.Linq;
using System.Text;
using System.IO;
using System.Diagnostics.Contracts;
using System.Web.UI.WebControls;
namespace System.Web.UI
{
public class HtmlTextWriter
{
public HtmlTextWriter(TextWriter writer)
{
Contract.Requires(writer != null);
}
public HtmlTextWriter(TextWriter writer, string tabString)
{
Contract.Requires(writer != null);
}
// public virtual void AddAttribute(string name, string value);
// public virtual void AddAttribute(HtmlTextWriterAttribute key, string value);
// public virtual void AddAttribute(string name, string value, bool fEndode);
// protected virtual void AddAttribute(string name, string value, HtmlTextWriterAttribute key);
// public virtual void AddAttribute(HtmlTextWriterAttribute key, string value, bool fEncode);
// public virtual void AddStyleAttribute(string name, string value);
// public virtual void AddStyleAttribute(HtmlTextWriterStyle key, string value);
// protected virtual void AddStyleAttribute(string name, string value, HtmlTextWriterStyle key);
// public virtual void BeginRender();
protected string EncodeAttributeValue(string value, bool fEncode)
{
Contract.Ensures(Contract.Result<string>() != null || value == null);
return default(string);
}
protected virtual string EncodeAttributeValue(HtmlTextWriterAttribute attrKey, string value)
{
Contract.Ensures(Contract.Result<string>() != null || value == null);
return default(string);
}
// protected string EncodeUrl(string url);
// public virtual void EndRender();
public virtual void EnterStyle(Style style)
{
Contract.Requires(style != null);
}
public virtual void EnterStyle(Style style, HtmlTextWriterTag tag)
{
Contract.Requires(style != null);
}
public virtual void ExitStyle(Style style)
{
Contract.Requires(style != null);
}
public virtual void ExitStyle(Style style, HtmlTextWriterTag tag)
{
Contract.Requires(style != null);
}
// protected virtual void FilterAttributes();
// public override void Flush();
[Pure]
protected HtmlTextWriterAttribute GetAttributeKey(string attrName)
{
return default(HtmlTextWriterAttribute);
}
[Pure]
protected string GetAttributeName(HtmlTextWriterAttribute attrKey)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
[Pure]
protected HtmlTextWriterStyle GetStyleKey(string styleName)
{
return default(HtmlTextWriterStyle);
}
[Pure]
protected string GetStyleName(HtmlTextWriterStyle styleKey)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
// protected virtual HtmlTextWriterTag GetTagKey(string tagName);
[Pure]
protected virtual string GetTagName(HtmlTextWriterTag tagKey)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
[Pure]
protected bool IsAttributeDefined(HtmlTextWriterAttribute key)
{
return default(bool);
}
[Pure]
protected bool IsAttributeDefined(HtmlTextWriterAttribute key, out string value)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out value) != null);
value = null;
return default(bool);
}
[Pure]
protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key)
{
return default(bool);
}
[Pure]
protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key, out string value)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out value) != null);
value = null;
return default(bool);
}
[Pure]
public virtual bool IsValidFormAttribute(string attribute)
{
return default(bool);
}
protected virtual bool OnAttributeRender(string name, string value, HtmlTextWriterAttribute key)
{
Contract.Requires(name != null);
Contract.Requires(value != null);
return default(bool);
}
protected virtual bool OnStyleAttributeRender(string name, string value, HtmlTextWriterStyle key)
{
Contract.Requires(name != null);
Contract.Requires(value != null);
return default(bool);
}
protected virtual bool OnTagRender(string name, HtmlTextWriterTag key)
{
Contract.Requires(name != null);
return default(bool);
}
// protected virtual void OutputTabs();
protected string PopEndTag()
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
protected void PushEndTag(string endTag)
{
Contract.Requires(endTag != null);
}
protected static void RegisterAttribute(string name, HtmlTextWriterAttribute key)
{
Contract.Requires(name != null);
}
protected static void RegisterStyle(string name, HtmlTextWriterStyle key)
{
Contract.Requires(name != null);
}
protected static void RegisterTag(string name, HtmlTextWriterTag key)
{
Contract.Requires(name != null);
}
//protected virtual string RenderAfterContent();
//protected virtual string RenderAfterTag();
//protected virtual string RenderBeforeContent();
//protected virtual string RenderBeforeTag();
//public virtual void RenderBeginTag(string tagName);
//public virtual void RenderBeginTag(HtmlTextWriterTag tagKey);
//public virtual void RenderEndTag();
//public override void Write(bool value);
#if false
public override void Write(char value);
public override void Write(char[] buffer);
public override void Write(double value);
public override void Write(int value);
public override void Write(long value);
public override void Write(object value);
public override void Write(float value);
public override void Write(string s);
public virtual void Write(string format, params object[] arg)
{
Contract.Requires(format != null);
Contract.Requires(args != null);
}
public override void Write(string format, object arg0)
{
Contract.Requires(format != null);
}
public override void Write(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
}
public override void Write(string format, object arg0, object arg1)
{
Contract.Requires(format != null);
}
#endif
//public virtual void WriteAttribute(string name, string value);
//public virtual void WriteAttribute(string name, string value, bool fEncode);
public virtual void WriteBeginTag(string tagName)
{
Contract.Requires(tagName != null);
}
//public virtual void WriteBreak();
public virtual void WriteEncodedText(string text)
{
Contract.Requires(text != null);
}
public virtual void WriteEncodedUrl(string url)
{
Contract.Requires(url != null);
}
public virtual void WriteEncodedUrlParameter(string urlText)
{
Contract.Requires(urlText != null);
}
public virtual void WriteEndTag(string tagName)
{
Contract.Requires(tagName != null);
}
public virtual void WriteFullBeginTag(string tagName)
{
Contract.Requires(tagName != null);
}
//public void WriteLineNoTabs(string s);
public virtual void WriteStyleAttribute(string name, string value)
{
Contract.Requires(name != null);
}
public virtual void WriteStyleAttribute(string name, string value, bool fEncode)
{
Contract.Requires(name != null);
}
protected void WriteUrlEncodedString(string text, bool argument)
{
Contract.Requires(text != null);
}
public int Indent
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
}
public TextWriter InnerWriter
{
get
{
Contract.Ensures(Contract.Result<TextWriter>() != null);
return default(TextWriter);
}
set
{
Contract.Requires(value != null);
}
}
// protected HtmlTextWriterTag TagKey { get; set; }
// protected string TagName { get; set; }
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS
{
using Microsoft.Modeling;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// The enumeration of record the prior operation.
/// </summary>
public enum PriorOperation
{
/// <summary>
/// The RopSynchronizationImportMessageMove operation.
/// </summary>
RopSynchronizationImportMessageMove,
/// <summary>
/// The RopSynchronizationImportMessageChange operation.
/// </summary>
RopSynchronizationImportMessageChange,
/// <summary>
/// The RopSynchronizationImportHierarchyChange operation.
/// </summary>
RopSynchronizationImportHierarchyChange,
/// <summary>
/// The RopSynchronizationOpenCollector operation.
/// </summary>
RopSynchronizationOpenCollector,
/// <summary>
/// The RopFastTransferDestinationConfigure operation.
/// </summary>
RopFastTransferDestinationConfigure,
/// <summary>
/// The RopFastTransferSourceCopyProperties operation
/// </summary>
RopFastTransferSourceCopyProperties,
/// <summary>
/// The RopFastTransferSourceCopyFolder operation
/// </summary>
RopFastTransferSourceCopyFolder,
/// <summary>
/// The SynchronizationUploadState operation
/// </summary>
SynchronizationUploadState,
/// <summary>
/// The RopCreateMessage operation
/// </summary>
RopCreateMessage,
/// <summary>
/// The RopSynchronizationGetTransferState operation
/// </summary>
RopSynchronizationGetTransferState,
/// <summary>
/// The RopSynchronizationConfigure operation
/// </summary>
RopSynchronizationConfigure,
/// <summary>
/// The RopFastTransferSourceCopyMessage operation
/// </summary>
RopFastTransferSourceCopyMessage
}
/// <summary>
/// The enumeration of record the prior download operation.
/// </summary>
public enum PriorDownloadOperation
{
/// <summary>
/// The RopFastTransferSourceCopyMessage operation
/// </summary>
RopFastTransferSourceCopyMessage,
/// <summary>
/// The RopFastTransferSourceCopyTo operation
/// </summary>
RopFastTransferSourceCopyTo,
/// <summary>
/// The RopFastTransferSourceCopyProperties operation
/// </summary>
RopFastTransferSourceCopyProperties,
/// <summary>
/// The RopFastTransferSourceCopyFolder operation
/// </summary>
RopFastTransferSourceCopyFolder,
/// <summary>
/// The RopSynchronizationConfigure operation
/// </summary>
RopSynchronizationConfigure,
/// <summary>
/// The RopSynchronizationGetTransferState operation
/// </summary>
RopSynchronizationGetTransferState
}
/// <summary>
/// The data for connection
/// </summary>
public struct ConnectionData
{
/// <summary>
/// Logon server or not
/// </summary>
public int LogonHandleIndex;
/// <summary>
/// The local Id count.
/// </summary>
public uint LocalIdCount;
/// <summary>
/// logOn folder type
/// </summary>
public LogonFlags LogonFolderType;
/// <summary>
/// Contains folder id
/// </summary>
public Sequence<AbstractFolder> FolderContainer;
/// <summary>
/// Contains message id
/// </summary>
public Sequence<AbstractMessage> MessageContainer;
/// <summary>
/// Contains attachment id
/// </summary>
public Sequence<AbstractAttachment> AttachmentContainer;
/// <summary>
/// The download contexts created on the server
/// </summary>
public Sequence<AbstractDownloadInfo> DownloadContextContainer;
/// <summary>
/// The upload contexts created on the server
/// </summary>
public Sequence<AbstractUploadInfo> UploadContextContainer;
}
/// <summary>
/// The abstract folder structure.
/// </summary>
public struct AbstractFolder
{
/// <summary>
/// Folder Id index of parent folder.
/// </summary>
public int ParentFolderIdIndex;
/// <summary>
/// Folder handle index of parent folder.
/// </summary>
public int ParentFolderHandleIndex;
/// <summary>
/// The folder Id index.
/// </summary>
public int FolderIdIndex;
/// <summary>
/// The folder handle index.
/// </summary>
public int FolderHandleIndex;
/// <summary>
/// The count of subFolder.
/// </summary>
public Set<int> SubFolderIds;
/// <summary>
/// The count of messages.
/// </summary>
public Set<int> MessageIds;
/// <summary>
/// The folder properties.
/// </summary>
public Set<string> FolderProperties;
/// <summary>
/// The change number index.
/// </summary>
public int ChangeNumberIndex;
/// <summary>
/// The folder permission.
/// </summary>
public PermissionLevels FolderPermission;
/// <summary>
/// Contains the ICS State have been downloaded.
/// </summary>
public MapContainer<int, AbstractUpdatedState> ICSStateContainer;
}
/// <summary>
/// The abstract Updated State structure.
/// </summary>
public struct AbstractUpdatedState
{
/// <summary>
/// Contains PidTagIdsetGiven.
/// </summary>
public Set<int> IdsetGiven;
/// <summary>
/// Contains PidTagCnsetSeen.
/// </summary>
public Set<int> CnsetSeen;
/// <summary>
/// Contains PidTagCnsetSeenFAI.
/// </summary>
public Set<int> CnsetSeenFAI;
/// <summary>
/// Contains PidTagCnsetRead.
/// </summary>
public Set<int> CnsetRead;
}
/// <summary>
/// The abstract message structure.
/// </summary>
public struct AbstractMessage
{
/// <summary>
/// The folder Id index.
/// </summary>
public int FolderIdIndex;
/// <summary>
/// The folder handle index.
/// </summary>
public int FolderHandleIndex;
/// <summary>
/// The message Id index.
/// </summary>
public int MessageIdIndex;
/// <summary>
/// The message handle index.
/// </summary>
public int MessageHandleIndex;
/// <summary>
/// The message is FAI or not.
/// </summary>
public bool IsFAImessage;
/// <summary>
/// The message is read or not.
/// </summary>
public bool IsRead;
/// <summary>
/// The count of the attachments.
/// </summary>
public int AttachmentCount;
/// <summary>
/// The message properties.
/// </summary>
public Sequence<string> MessageProperties;
/// <summary>
/// The change number index.
/// </summary>
public int ChangeNumberIndex;
/// <summary>
/// The readState Change Number
/// </summary>
public int ReadStateChangeNumberIndex;
}
/// <summary>
/// The abstract attachment structure.
/// </summary>
public struct AbstractAttachment
{
/// <summary>
/// The attachment handle index.
/// </summary>
public int AttachmentHandleIndex;
}
/// <summary>
/// The abstract download context
/// </summary>
public struct AbstractDownloadInfo
{
/// <summary>
/// The messaging object type generate the download context.
/// </summary>
public ObjectType ObjectType;
/// <summary>
/// The relative messaging object handle index generate the download context.
/// </summary>
public int RelatedObjectHandleIndex;
/// <summary>
/// The download handle index.
/// </summary>
public int DownloadHandleIndex;
/// <summary>
/// The configuration for the FastTransfer stream.
/// </summary>
public FastTransferStreamType AbstractFastTransferStreamType;
/// <summary>
/// The stream index for download index.
/// </summary>
public int DownloadStreamIndex;
/// <summary>
/// The relative SendOptions
/// </summary>
public SendOptionAlls Sendoptions;
/// <summary>
/// Save the copyFlag type of CopyFolder operation
/// </summary>
public CopyFolderCopyFlags CopyFolderCopyFlag;
/// <summary>
/// Save the copypFlag type of CopyProperties operation
/// </summary>
public CopyPropertiesCopyFlags CopyPropertiesCopyFlag;
/// <summary>
/// Save the copyFlag type of CopyTo operation
/// </summary>
public CopyToCopyFlags CopyToCopyFlag;
/// <summary>
/// Save the copyFlag type of CopyMessage operation
/// </summary>
public RopFastTransferSourceCopyMessagesCopyFlags CopyMessageCopyFlag;
/// <summary>
/// Variable to indicate which FastTransfer Operation is called
/// </summary>
public EnumFastTransferOperation RelatedFastTransferOperation;
/// <summary>
/// The relative SynchronizationFlag
/// </summary>
public SynchronizationFlag Synchronizationflag;
/// <summary>
/// The relative SynchronizationExtraflag
/// </summary>
public SynchronizationExtraFlag SynchronizationExtraflag;
/// <summary>
/// The relative Property
/// </summary>
public Sequence<string> Property;
/// <summary>
/// The updated ICS state.
/// </summary>
public AbstractUpdatedState UpdatedState;
/// <summary>
/// The synchronization type.
/// </summary>
public SynchronizationTypes SynchronizationType;
/// <summary>
/// Indicates whether descendant sub-objects are copied.
/// </summary>
public bool IsLevelTrue;
}
/// <summary>
/// The abstract upload context
/// </summary>
public struct AbstractUploadInfo
{
/// <summary>
/// The relative messaging object handle index generate the upload context.
/// </summary>
public int RelatedObjectHandleIndex;
/// <summary>
/// The related object id index.
/// </summary>
public int RelatedObjectIdIndex;
/// <summary>
/// The upload handle index.
/// </summary>
public int UploadHandleIndex;
/// <summary>
/// The synchronization type.
/// </summary>
public SynchronizationTypes SynchronizationType;
/// <summary>
/// The relative ImportDeleteflags.
/// </summary>
public byte ImportDeleteflags;
/// <summary>
/// Identify the result whether is newerClientChange or not.
/// </summary>
public bool IsnewerClientChange;
/// <summary>
/// Variable to indicate which FastTransfer Operation is called
/// </summary>
public EnumFastTransferOperation RelatedFastTransferOperation;
/// <summary>
/// The updated ICS state.
/// </summary>
public AbstractUpdatedState UpdatedState;
}
/// <summary>
/// Helper class of Model
/// </summary>
public static class ModelHelper
{
/// <summary>
/// The change number index.
/// </summary>
private static int changeNumberIndex = 0;
/// <summary>
/// Requirement capture
/// </summary>
/// <param name="id">Requirement id</param>
/// <param name="description">Requirement description</param>
public static void CaptureRequirement(int id, string description)
{
Requirement.Capture(RequirementId.Make("MS-OXCFXICS", id, description));
}
/// <summary>
/// Assign a new change number.
/// </summary>
/// <returns>The current change number.</returns>
public static int GetChangeNumberIndex()
{
int tempChangeNumberIndex = ++changeNumberIndex;
return tempChangeNumberIndex;
}
}
}
| |
// 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.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class CmsSigner
{
private static readonly Oid s_defaultAlgorithm = Oid.FromOidValue(Oids.Sha256, OidGroup.HashAlgorithm);
private SubjectIdentifierType _signerIdentifierType;
public X509Certificate2 Certificate { get; set; }
public AsymmetricAlgorithm PrivateKey { get; set; }
public X509Certificate2Collection Certificates { get; private set; } = new X509Certificate2Collection();
public Oid DigestAlgorithm { get; set; }
public X509IncludeOption IncludeOption { get; set; }
public CryptographicAttributeObjectCollection SignedAttributes { get; private set; } = new CryptographicAttributeObjectCollection();
public CryptographicAttributeObjectCollection UnsignedAttributes { get; private set; } = new CryptographicAttributeObjectCollection();
public SubjectIdentifierType SignerIdentifierType
{
get { return _signerIdentifierType; }
set
{
if (value < SubjectIdentifierType.IssuerAndSerialNumber || value > SubjectIdentifierType.NoSignature)
throw new ArgumentException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, value));
_signerIdentifierType = value;
}
}
public CmsSigner()
: this(SubjectIdentifierType.IssuerAndSerialNumber, null)
{
}
public CmsSigner(SubjectIdentifierType signerIdentifierType)
: this(signerIdentifierType, null)
{
}
public CmsSigner(X509Certificate2 certificate)
: this(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
{
}
// This can be implemented with NETCOREAPP2_0 with the cert creation API.
// * Open the parameters as RSACSP (RSA PKCS#1 signature was hard-coded in netfx)
// * Which will fail on non-Windows
// * Create a certificate with subject CN=CMS Signer Dummy Certificate
// * Need to check against NetFx to find out what the NotBefore/NotAfter values are
// * No extensions
//
// Since it would only work on Windows, it could also be just done as P/Invokes to
// CertCreateSelfSignedCertificate on a split Windows/netstandard implementation.
public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) : this(signerIdentifierType, certificate, null)
{
}
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate, AsymmetricAlgorithm privateKey)
{
switch (signerIdentifierType)
{
case SubjectIdentifierType.Unknown:
_signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.IssuerAndSerialNumber:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.NoSignature:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.None;
break;
default:
_signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
}
Certificate = certificate;
DigestAlgorithm = new Oid(s_defaultAlgorithm);
PrivateKey = privateKey;
}
internal void CheckCertificateValue()
{
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
{
return;
}
if (Certificate == null)
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
if (PrivateKey == null && !Certificate.HasPrivateKey)
{
throw new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
}
}
internal SignerInfoAsn Sign(
ReadOnlyMemory<byte> data,
string contentTypeOid,
bool silent,
out X509Certificate2Collection chainCerts)
{
HashAlgorithmName hashAlgorithmName = PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm);
IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName);
hasher.AppendData(data.Span);
byte[] dataHash = hasher.GetHashAndReset();
SignerInfoAsn newSignerInfo = new SignerInfoAsn();
newSignerInfo.DigestAlgorithm.Algorithm = DigestAlgorithm;
// If the user specified attributes (not null, count > 0) we need attributes.
// If the content type is null we're counter-signing, and need the message digest attr.
// If the content type is otherwise not-data we need to record it as the content-type attr.
if (SignedAttributes?.Count > 0 || contentTypeOid != Oids.Pkcs7Data)
{
List<AttributeAsn> signedAttrs = BuildAttributes(SignedAttributes);
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.WriteOctetString(dataHash);
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.MessageDigest, Oids.MessageDigest),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
});
}
if (contentTypeOid != null)
{
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.WriteObjectIdentifier(contentTypeOid);
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.ContentType, Oids.ContentType),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
});
}
}
// Use the serializer/deserializer to DER-normalize the attribute order.
SignedAttributesSet signedAttrsSet = new SignedAttributesSet();
signedAttrsSet.SignedAttributes = PkcsHelpers.NormalizeAttributeSet(
signedAttrs.ToArray(),
normalized => hasher.AppendData(normalized));
// Since this contains user data in a context where BER is permitted, use BER.
// There shouldn't be any observable difference here between BER and DER, though,
// since the top level fields were written by NormalizeSet.
using (AsnWriter attrsWriter = new AsnWriter(AsnEncodingRules.BER))
{
signedAttrsSet.Encode(attrsWriter);
newSignerInfo.SignedAttributes = attrsWriter.Encode();
}
dataHash = hasher.GetHashAndReset();
}
switch (SignerIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
byte[] serial = Certificate.GetSerialNumber();
Array.Reverse(serial);
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = Certificate.IssuerName.RawData,
SerialNumber = serial,
};
newSignerInfo.Version = 1;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate);
newSignerInfo.Version = 3;
break;
case SubjectIdentifierType.NoSignature:
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = SubjectIdentifier.DummySignerEncodedValue,
SerialNumber = new byte[1],
};
newSignerInfo.Version = 1;
break;
default:
Debug.Fail($"Unresolved SignerIdentifierType value: {SignerIdentifierType}");
throw new CryptographicException();
}
if (UnsignedAttributes != null && UnsignedAttributes.Count > 0)
{
List<AttributeAsn> attrs = BuildAttributes(UnsignedAttributes);
newSignerInfo.UnsignedAttributes = PkcsHelpers.NormalizeAttributeSet(attrs.ToArray());
}
bool signed;
Oid signatureAlgorithm;
ReadOnlyMemory<byte> signatureValue;
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
{
signatureAlgorithm = new Oid(Oids.NoSignature, null);
signatureValue = dataHash;
signed = true;
}
else
{
signed = CmsSignature.Sign(
dataHash,
hashAlgorithmName,
Certificate,
PrivateKey,
silent,
out signatureAlgorithm,
out signatureValue);
}
if (!signed)
{
throw new CryptographicException(SR.Cryptography_Cms_CannotDetermineSignatureAlgorithm);
}
newSignerInfo.SignatureValue = signatureValue;
newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.AddRange(Certificates);
if (SignerIdentifierType != SubjectIdentifierType.NoSignature)
{
if (IncludeOption == X509IncludeOption.EndCertOnly)
{
certs.Add(Certificate);
}
else if (IncludeOption != X509IncludeOption.None)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
if (!chain.Build(Certificate))
{
foreach (X509ChainStatus status in chain.ChainStatus)
{
if (status.Status == X509ChainStatusFlags.PartialChain)
{
throw new CryptographicException(SR.Cryptography_Cms_IncompleteCertChain);
}
}
}
X509ChainElementCollection elements = chain.ChainElements;
int count = elements.Count;
int last = count - 1;
if (last == 0)
{
// If there's always one cert treat it as EE, not root.
last = -1;
}
for (int i = 0; i < count; i++)
{
X509Certificate2 cert = elements[i].Certificate;
if (i == last &&
IncludeOption == X509IncludeOption.ExcludeRoot &&
cert.SubjectName.RawData.AsSpan().SequenceEqual(cert.IssuerName.RawData))
{
break;
}
certs.Add(cert);
}
}
}
chainCerts = certs;
return newSignerInfo;
}
internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection attributes)
{
List<AttributeAsn> signedAttrs = new List<AttributeAsn>();
if (attributes == null || attributes.Count == 0)
{
return signedAttrs;
}
foreach (CryptographicAttributeObject attributeObject in attributes)
{
AttributeAsn newAttr = new AttributeAsn
{
AttrType = attributeObject.Oid,
AttrValues = new ReadOnlyMemory<byte>[attributeObject.Values.Count],
};
for (int i = 0; i < attributeObject.Values.Count; i++)
{
newAttr.AttrValues[i] = attributeObject.Values[i].RawData;
}
signedAttrs.Add(newAttr);
}
return signedAttrs;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddBraces
{
public partial class AddBracesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(new CSharpAddBracesDiagnosticAnalyzer(),
new CSharpAddBracesCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForIfWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|if|] (true)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForElseWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
if (true)
{
return;
}
[|else|]
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForElseWithChildIf()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
if (true)
return;
[|else|] if (false)
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForForWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|for|] (var i = 0; i < 5; i++)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForForEachWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|foreach|] (var c in ""test"")
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForWhileWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|while|] (true)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForDoWhileWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|do|]
{
return;
}
while (true);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForUsingWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForUsingWithChildUsing()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
using (var b = new Buzz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForLockWithBraces()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
var str = ""test"";
[|lock|] (str)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForLockWithChildLock()
{
await TestMissingAsync(
@"class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
[|lock|] (str1)
lock (str2)
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForIfWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|if|] (true) return;
}
}",
@"
class Program
{
static void Main()
{
if (true)
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForElseWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
if (true) { return; }
[|else|] return;
}
}",
@"
class Program
{
static void Main()
{
if (true) { return; }
else
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForIfNestedInElseWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
if (true) return;
else [|if|] (false) return;
}
}",
@"
class Program
{
static void Main()
{
if (true) return;
else if (false)
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForForWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|for|] (var i = 0; i < 5; i++) return;
}
}",
@"
class Program
{
static void Main()
{
for (var i = 0; i < 5; i++)
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForForEachWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|foreach|] (var c in ""test"") return;
}
}",
@"
class Program
{
static void Main()
{
foreach (var c in ""test"")
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForWhileWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|while|] (true) return;
}
}",
@"
class Program
{
static void Main()
{
while (true)
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForDoWhileWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|do|] return; while (true);
}
}",
@"
class Program
{
static void Main()
{
do
{
return;
}
while (true);
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForUsingWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForUsingWithoutBracesNestedInUsing()
{
await TestAsync(
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
[|using|] (var b = new Buzz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
using (var b = new Buzz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForLockWithoutBraces()
{
await TestAsync(
@"
class Program
{
static void Main()
{
var str = ""test"";
[|lock|] (str)
return;
}
}",
@"
class Program
{
static void Main()
{
var str = ""test"";
lock (str)
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForLockWithoutBracesNestedInLock()
{
await TestAsync(
@"
class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
lock (str1)
[|lock|] (str2) // VS thinks this should be indented one more level
return;
}
}",
@"
class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
lock (str1)
lock (str2) // VS thinks this should be indented one more level
{
return;
}
}
}",
index: 0,
compareTokens: false);
}
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class UnlitGUI : BaseUnlitGUI
{
protected override uint defaultExpandedState { get { return (uint)(Expandable.Base | Expandable.Input | Expandable.Transparency); } }
protected static class Styles
{
public static string InputsText = "Surface Inputs";
public static GUIContent colorText = new GUIContent("Color", " Albedo (RGB) and Transparency (A).");
public static string emissiveLabelText = "Emission Inputs";
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive Color (RGB).");
// Emissive
public static GUIContent albedoAffectEmissiveText = new GUIContent("Emission multiply with Base", "Specifies whether or not the emission color is multiplied by the albedo.");
public static GUIContent useEmissiveIntensityText = new GUIContent("Use Emission Intensity", "Specifies whether to use to a HDR color or a LDR color with a separate multiplier.");
public static GUIContent emissiveIntensityText = new GUIContent("Emission Intensity", "");
public static GUIContent emissiveIntensityFromHDRColorText = new GUIContent("The emission intensity is from the HDR color picker in luminance", "");
public static GUIContent emissiveExposureWeightText = new GUIContent("Exposure weight", "Control the percentage of emission to expose.");
}
protected MaterialProperty color = null;
protected const string kColor = "_UnlitColor";
protected MaterialProperty colorMap = null;
protected const string kColorMap = "_UnlitColorMap";
protected MaterialProperty emissiveColor = null;
protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty emissiveColorLDR = null;
protected const string kEmissiveColorLDR = "_EmissiveColorLDR";
protected MaterialProperty emissiveExposureWeight = null;
protected const string kemissiveExposureWeight = "_EmissiveExposureWeight";
protected MaterialProperty useEmissiveIntensity = null;
protected const string kUseEmissiveIntensity = "_UseEmissiveIntensity";
protected MaterialProperty emissiveIntensityUnit = null;
protected const string kEmissiveIntensityUnit = "_EmissiveIntensityUnit";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected const string kStencilRef = "_StencilRef";
protected const string kStencilWriteMask = "_StencilWriteMask";
protected const string kStencilRefDepth = "_StencilRefDepth";
protected const string kStencilWriteMaskDepth = "_StencilWriteMaskDepth";
protected const string kStencilRefMV = "_StencilRefMV";
protected const string kStencilWriteMaskMV = "_StencilWriteMaskMV";
protected const string kStencilRefDistortionVec = "_StencilRefDistortionVec";
protected const string kStencilWriteMaskDistortionVec = "_StencilWriteMaskDistortionVec";
override protected void FindMaterialProperties(MaterialProperty[] props)
{
color = FindProperty(kColor, props);
colorMap = FindProperty(kColorMap, props);
emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensityUnit = FindProperty(kEmissiveIntensityUnit, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
emissiveExposureWeight = FindProperty(kemissiveExposureWeight, props);
emissiveColorLDR = FindProperty(kEmissiveColorLDR, props);
useEmissiveIntensity = FindProperty(kUseEmissiveIntensity, props);
}
protected override void MaterialPropertiesGUI(Material material)
{
using (var header = new HeaderScope(Styles.InputsText, (uint)Expandable.Input, this))
{
if (header.expanded)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.colorText, colorMap, color);
m_MaterialEditor.TextureScaleOffsetProperty(colorMap);
}
}
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent)
{
using (var header = new HeaderScope(StylesBaseUnlit.TransparencyInputsText, (uint)Expandable.Transparency, this))
{
if (header.expanded)
{
DoDistortionInputsGUI();
}
}
}
using (var header = new HeaderScope(Styles.emissiveLabelText, (uint)Expandable.Emissive, this))
{
if (header.expanded)
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(useEmissiveIntensity, Styles.useEmissiveIntensityText);
bool updateEmissiveColor = EditorGUI.EndChangeCheck();
if (useEmissiveIntensity.floatValue == 0)
{
EditorGUI.BeginChangeCheck();
DoEmissiveTextureProperty(material, emissiveColor);
if (EditorGUI.EndChangeCheck() || updateEmissiveColor)
emissiveColor.colorValue = emissiveColor.colorValue;
EditorGUILayout.HelpBox(Styles.emissiveIntensityFromHDRColorText.text, MessageType.Info, true);
}
else
{
EditorGUI.BeginChangeCheck();
{
DoEmissiveTextureProperty(material, emissiveColorLDR);
emissiveColorLDR.colorValue = NormalizeEmissionColor(ref updateEmissiveColor, emissiveColorLDR.colorValue);
using (new EditorGUILayout.HorizontalScope())
{
EmissiveIntensityUnit unit = (EmissiveIntensityUnit)emissiveIntensityUnit.floatValue;
if (unit == EmissiveIntensityUnit.Luminance)
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
else
{
float evValue = LightUtils.ConvertLuminanceToEv(emissiveIntensity.floatValue);
evValue = EditorGUILayout.FloatField(Styles.emissiveIntensityText, evValue);
emissiveIntensity.floatValue = LightUtils.ConvertEvToLuminance(evValue);
}
emissiveIntensityUnit.floatValue = (float)(EmissiveIntensityUnit)EditorGUILayout.EnumPopup(unit);
}
}
if (EditorGUI.EndChangeCheck() || updateEmissiveColor)
emissiveColor.colorValue = emissiveColorLDR.colorValue * emissiveIntensity.floatValue;
}
m_MaterialEditor.ShaderProperty(emissiveExposureWeight, Styles.emissiveExposureWeightText);
DoEmissionArea(material);
}
}
}
void DoEmissiveTextureProperty(Material material, MaterialProperty color)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, color);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
}
protected override void MaterialPropertiesAdvanceGUI(Material material)
{
}
protected override void VertexAnimationPropertiesGUI()
{
}
protected override bool ShouldEmissionBeEnabled(Material material)
{
return (material.GetColor(kEmissiveColor) != Color.black) || material.GetTexture(kEmissiveColorMap);
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)
{
SetupMaterialKeywordsAndPass(material);
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static public void SetupMaterialKeywordsAndPass(Material material)
{
SetupBaseUnlitKeywords(material);
SetupBaseUnlitMaterialPass(material);
CoreUtils.SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
// Stencil usage rules:
// DoesntReceiveSSR and DecalsForwardOutputNormalBuffer need to be tagged during depth prepass
// LightingMask need to be tagged during either GBuffer or Forward pass
// ObjectVelocity need to be tagged in velocity pass.
// As velocity pass can be use as a replacement of depth prepass it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer
// As GBuffer pass can have no depth prepass, it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer
// Object velocity is always render after a full depth buffer (if there is no depth prepass for GBuffer all object motion vectors are render after GBuffer)
// so we have a guarantee than when we write object velocity no other object will be draw on top (and so would have require to overwrite velocity).
// Final combination is:
// Prepass: DoesntReceiveSSR, DecalsForwardOutputNormalBuffer
// Motion vectors: DoesntReceiveSSR, DecalsForwardOutputNormalBuffer, ObjectVelocity
// Forward: LightingMask
int stencilRef = (int)StencilLightingUsage.NoLighting;
int stencilWriteMask = (int)HDRenderPipeline.StencilBitMask.LightingMask;
int stencilRefDepth = (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR;
int stencilWriteMaskDepth = (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer;
int stencilRefMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors | (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR;
int stencilWriteMaskMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors | (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer;
// As we tag both during velocity pass and Gbuffer pass we need a separate state and we need to use the write mask
material.SetInt(kStencilRef, stencilRef);
material.SetInt(kStencilWriteMask, stencilWriteMask);
material.SetInt(kStencilRefDepth, stencilRefDepth);
material.SetInt(kStencilWriteMaskDepth, stencilWriteMaskDepth);
material.SetInt(kStencilRefMV, stencilRefMV);
material.SetInt(kStencilWriteMaskMV, stencilWriteMaskMV);
material.SetInt(kStencilRefDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors);
material.SetInt(kStencilWriteMaskDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors);
}
}
} // namespace UnityEditor
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
using System.Numerics;
#endif
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenWriterTest : TestFixtureBase
{
[Test]
public void ValueFormatting()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world.");
JToken root;
using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteValue(data);
jsonWriter.WriteEndArray();
root = jsonWriter.Token;
}
CustomAssert.IsInstanceOfType(typeof(JArray), root);
Assert.AreEqual(13, root.Children().Count());
Assert.AreEqual("@", (string)root[0]);
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
Assert.AreEqual(true, (bool)root[2]);
Assert.AreEqual(10, (int)root[3]);
Assert.AreEqual(10.99, (double)root[4]);
Assert.AreEqual(0.99, (double)root[5]);
Assert.AreEqual(0.000000000000000001d, (double)root[6]);
Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
Assert.AreEqual(string.Empty, (string)root[8]);
Assert.AreEqual("This is a string.", (string)root[9]);
Assert.AreEqual(null, ((JValue)root[10]).Value);
Assert.AreEqual(null, ((JValue)root[11]).Value);
Assert.AreEqual(data, (byte[])root[12]);
}
[Test]
public void State()
{
using (JsonWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
}
[Test]
public void WriteComment()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteComment("fail");
writer.WriteEndArray();
Assert.AreEqual(@"[
/*fail*/]", writer.Token.ToString());
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
[Test]
public void WriteBigInteger()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteValue(new BigInteger(123));
writer.WriteEndArray();
JValue i = (JValue) writer.Token[0];
Assert.AreEqual(new BigInteger(123), i.Value);
Assert.AreEqual(JTokenType.Integer, i.Type);
Assert.AreEqual(@"[
123
]", writer.Token.ToString());
}
#endif
[Test]
public void WriteRaw()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRaw("fail");
writer.WriteRaw("fail");
writer.WriteEndArray();
// this is a bug. write raw shouldn't be autocompleting like this
// hard to fix without introducing Raw and RawValue token types
// meh
Assert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteRawValue()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRawValue("fail");
writer.WriteRawValue("fail");
writer.WriteEndArray();
Assert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void DateTimeZoneHandling()
{
JTokenWriter writer = new JTokenWriter
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
JValue value = (JValue) writer.Token;
DateTime dt = (DateTime)value.Value;
Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if XMLCHARTYPE_GEN_RESOURCE
#undef XMLCHARTYPE_USE_RESOURCE
#endif
//#define XMLCHARTYPE_USE_RESOURCE // load the character properties from resources (XmlCharType.bin must be linked to assembly)
//#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin
#if XMLCHARTYPE_GEN_RESOURCE || XMLCHARTYPE_USE_RESOURCE
using System.IO;
using System.Reflection;
#endif
using System.Threading;
using System.Diagnostics;
namespace System.Xml
{
/// <internalonly/>
/// <devdoc>
/// The XmlCharType class is used for quick character type recognition
/// which is optimized for the first 127 ascii characters.
/// </devdoc>
#if XMLCHARTYPE_USE_RESOURCE
internal unsafe struct XmlCharType {
#else
internal struct XmlCharType
{
#endif
// Surrogate constants
internal const int SurHighStart = 0xd800; // 1101 10xx
internal const int SurHighEnd = 0xdbff;
internal const int SurLowStart = 0xdc00; // 1101 11xx
internal const int SurLowEnd = 0xdfff;
internal const int SurMask = 0xfc00; // 1111 11xx
#if XML10_FIFTH_EDITION
// Characters defined in the XML 1.0 Fifth Edition
// Whitespace chars -- Section 2.3 [3]
// Star NCName characters -- Section 2.3 [4] (NameStartChar characters without ':')
// NCName characters -- Section 2.3 [4a] (NameChar characters without ':')
// Character data characters -- Section 2.2 [2]
// Public ID characters -- Section 2.3 [13]
// Characters defined in the XML 1.0 Fourth Edition
// NCNameCharacters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier - minus the ':' char per the Namespaces in XML spec
// Letter characters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier
// This appendix has been deprecated in XML 1.0 5th edition, but we still need to use
// the Letter and NCName definitions from the 4th edition in some places because of backwards compatibility
internal const int fWhitespace = 1;
internal const int fLetter = 2;
internal const int fNCStartNameSC = 4; // SC = Single Char
internal const int fNCNameSC = 8; // SC = Single Char
internal const int fCharData = 16;
internal const int fNCNameXml4e = 32; // NCName char according to the XML 1.0 4th edition
internal const int fText = 64;
internal const int fAttrValue = 128;
// name surrogate constants
private const int s_NCNameSurCombinedStart = 0x10000;
private const int s_NCNameSurCombinedEnd = 0xEFFFF;
private const int s_NCNameSurHighStart = SurHighStart + ((s_NCNameSurCombinedStart - 0x10000) / 1024);
private const int s_NCNameSurHighEnd = SurHighStart + ((s_NCNameSurCombinedEnd - 0x10000) / 1024);
private const int s_NCNameSurLowStart = SurLowStart + ((s_NCNameSurCombinedStart - 0x10000) % 1024);
private const int s_NCNameSurLowEnd = SurLowStart + ((s_NCNameSurCombinedEnd - 0x10000) % 1024);
#else
// Characters defined in the XML 1.0 Fourth Edition
// Whitespace chars -- Section 2.3 [3]
// Letters -- Appendix B [84]
// Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':')
// NCName characters -- Section 2.3 [4] (Name characters without ':')
// Character data characters -- Section 2.2 [2]
// PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
internal const int fWhitespace = 1;
internal const int fLetter = 2;
internal const int fNCStartNameSC = 4;
internal const int fNCNameSC = 8;
internal const int fCharData = 16;
internal const int fNCNameXml4e = 32;
internal const int fText = 64;
internal const int fAttrValue = 128;
#endif
// bitmap for public ID characters - 1 bit per character 0x0 - 0x80; no character > 0x80 is a PUBLIC ID char
private const string s_PublicIdBitmap = "\u2400\u0000\uffbb\uafff\uffff\u87ff\ufffe\u07ff";
// size of XmlCharType table
private const uint CharPropertiesSize = (uint)char.MaxValue + 1;
#if !XMLCHARTYPE_USE_RESOURCE || XMLCHARTYPE_GEN_RESOURCE
internal const string s_Whitespace =
"\u0009\u000a\u000d\u000d\u0020\u0020";
#if XML10_FIFTH_EDITION
// StartNameChar without ':' -- see Section 2.3 production [4]
const string s_NCStartName =
"\u0041\u005a\u005f\u005f\u0061\u007a\u00c0\u00d6" +
"\u00d8\u00f6\u00f8\u02ff\u0370\u037d\u037f\u1fff" +
"\u200c\u200d\u2070\u218f\u2c00\u2fef\u3001\ud7ff" +
"\uf900\ufdcf\ufdf0\ufffd";
// NameChar without ':' -- see Section 2.3 production [4a]
const string s_NCName =
"\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" +
"\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u037d\u037f\u1fff\u200c\u200d\u203f\u2040" +
"\u2070\u218f\u2c00\u2fef\u3001\ud7ff\uf900\ufdcf" +
"\ufdf0\ufffd";
#else
const string s_NCStartName =
"\u0041\u005a\u005f\u005f\u0061\u007a" +
"\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" +
"\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" +
"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" +
"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" +
"\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" +
"\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" +
"\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" +
"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" +
"\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" +
"\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" +
"\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" +
"\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" +
"\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" +
"\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" +
"\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" +
"\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" +
"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" +
"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" +
"\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" +
"\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" +
"\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" +
"\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" +
"\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" +
"\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" +
"\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" +
"\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" +
"\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" +
"\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" +
"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" +
"\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" +
"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" +
"\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" +
"\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" +
"\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" +
"\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" +
"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" +
"\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" +
"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" +
"\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" +
"\u4e00\u9fa5\uac00\ud7a3";
const string s_NCName =
"\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" +
"\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" +
"\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" +
"\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" +
"\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" +
"\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" +
"\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" +
"\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +
"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" +
"\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" +
"\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" +
"\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" +
"\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" +
"\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +
"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +
"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" +
"\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" +
"\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" +
"\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +
"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" +
"\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" +
"\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" +
"\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" +
"\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" +
"\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +
"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" +
"\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" +
"\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" +
"\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" +
"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" +
"\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" +
"\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +
"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" +
"\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" +
"\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" +
"\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +
"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" +
"\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" +
"\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" +
"\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" +
"\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" +
"\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +
"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" +
"\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
#endif
const string s_CharData =
"\u0009\u000a\u000d\u000d\u0020\ud7ff\ue000\ufffd";
const string s_PublicID =
"\u000a\u000a\u000d\u000d\u0020\u0021\u0023\u0025" +
"\u0027\u003b\u003d\u003d\u003f\u005a\u005f\u005f" +
"\u0061\u007a";
const string s_Text = // TextChar = CharData - { 0xA | 0xD | '<' | '&' | 0x9 | ']' | 0xDC00 - 0xDFFF }
"\u0020\u0025\u0027\u003b\u003d\u005c\u005e\ud7ff\ue000\ufffd";
const string s_AttrValue = // AttrValueChar = CharData - { 0xA | 0xD | 0x9 | '<' | '>' | '&' | '\'' | '"' | 0xDC00 - 0xDFFF }
"\u0020\u0021\u0023\u0025\u0028\u003b\u003d\u003d\u003f\ud7ff\ue000\ufffd";
//
// XML 1.0 Fourth Edition definitions for name characters
//
const string s_LetterXml4e =
"\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u0386\u0386\u0388\u038a" +
"\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6" +
"\u03da\u03da\u03dc\u03dc\u03de\u03de\u03e0\u03e0" +
"\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" +
"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc" +
"\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9\u0531\u0556" +
"\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2" +
"\u0621\u063a\u0641\u064a\u0671\u06b7\u06ba\u06be" +
"\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6" +
"\u0905\u0939\u093d\u093d\u0958\u0961\u0985\u098c" +
"\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" +
"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1" +
"\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30" +
"\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c" +
"\u0a5e\u0a5e\u0a72\u0a74\u0a85\u0a8b\u0a8d\u0a8d" +
"\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3" +
"\u0ab5\u0ab9\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c" +
"\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" +
"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61" +
"\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a" +
"\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" +
"\u0bae\u0bb5\u0bb7\u0bb9\u0c05\u0c0c\u0c0e\u0c10" +
"\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61" +
"\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" +
"\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" +
"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61" +
"\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33\u0e40\u0e45" +
"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a" +
"\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3" +
"\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae" +
"\u0eb0\u0eb0\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4" +
"\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" +
"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094" +
"\u30a1\u30fa\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
const string s_NCNameXml4e =
"\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" +
"\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" +
"\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" +
"\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" +
"\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" +
"\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" +
"\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" +
"\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +
"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" +
"\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" +
"\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" +
"\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" +
"\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" +
"\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +
"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +
"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" +
"\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" +
"\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" +
"\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +
"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" +
"\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" +
"\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" +
"\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" +
"\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" +
"\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +
"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" +
"\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" +
"\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" +
"\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" +
"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" +
"\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" +
"\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +
"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" +
"\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" +
"\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" +
"\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +
"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" +
"\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" +
"\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" +
"\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" +
"\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" +
"\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +
"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" +
"\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
#endif
// static lock for XmlCharType class
private static object s_Lock;
private static object StaticLock
{
get
{
if (s_Lock == null)
{
object o = new object();
Interlocked.CompareExchange<object>(ref s_Lock, o, null);
}
return s_Lock;
}
}
#if XMLCHARTYPE_USE_RESOURCE
private static volatile byte* s_CharProperties;
internal byte* charProperties;
static void InitInstance() {
lock ( StaticLock ) {
if ( s_CharProperties != null ) {
return;
}
UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)Assembly.GetExecutingAssembly().GetManifestResourceStream( "XmlCharType.bin" );
Debug.Assert( memStream.Length == CharPropertiesSize );
byte* chProps = memStream.PositionPointer;
Thread.MemoryBarrier(); // For weak memory models (IA64)
s_CharProperties = chProps;
}
}
#else // !XMLCHARTYPE_USE_RESOURCE
private static volatile byte[] s_CharProperties;
internal byte[] charProperties;
static void InitInstance()
{
lock (StaticLock)
{
if (s_CharProperties != null)
{
return;
}
byte[] chProps = new byte[CharPropertiesSize];
SetProperties(chProps, s_Whitespace, fWhitespace);
SetProperties(chProps, s_LetterXml4e, fLetter);
SetProperties(chProps, s_NCStartName, fNCStartNameSC);
SetProperties(chProps, s_NCName, fNCNameSC);
SetProperties(chProps, s_CharData, fCharData);
SetProperties(chProps, s_NCNameXml4e, fNCNameXml4e);
SetProperties(chProps, s_Text, fText);
SetProperties(chProps, s_AttrValue, fAttrValue);
s_CharProperties = chProps;
}
}
private static void SetProperties(byte[] chProps, string ranges, byte value)
{
for (int p = 0; p < ranges.Length; p += 2)
{
for (int i = ranges[p], last = ranges[p + 1]; i <= last; i++)
{
chProps[i] |= value;
}
}
}
#endif
#if XMLCHARTYPE_USE_RESOURCE
private XmlCharType( byte* charProperties ) {
#else
private XmlCharType(byte[] charProperties)
{
#endif
Debug.Assert(s_CharProperties != null);
this.charProperties = charProperties;
}
public static XmlCharType Instance
{
get
{
if (s_CharProperties == null)
{
InitInstance();
}
return new XmlCharType(s_CharProperties);
}
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsWhiteSpace(char ch)
{
return (charProperties[ch] & fWhitespace) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsNCNameSingleChar(char ch)
{
return (charProperties[ch] & fNCNameSC) != 0;
}
#if XML10_FIFTH_EDITION
public bool IsNCNameSurrogateChar(string str, int index)
{
if (index + 1 >= str.Length)
{
return false;
}
return InRange(str[index], s_NCNameSurHighStart, s_NCNameSurHighEnd) &&
InRange(str[index + 1], s_NCNameSurLowStart, s_NCNameSurLowEnd);
}
// Surrogate characters for names are the same for NameChar and StartNameChar,
// so this method can be used for both
public bool IsNCNameSurrogateChar(char lowChar, char highChar)
{
return InRange(highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd) &&
InRange(lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd);
}
public bool IsNCNameHighSurrogateChar(char highChar)
{
return InRange(highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd);
}
public bool IsNCNameLowSurrogateChar(char lowChar)
{
return InRange(lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd);
}
#endif
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsStartNCNameSingleChar(char ch)
{
return (charProperties[ch] & fNCStartNameSC) != 0;
}
public bool IsNameSingleChar(char ch)
{
return IsNCNameSingleChar(ch) || ch == ':';
}
#if XML10_FIFTH_EDITION
public bool IsNameSurrogateChar(char lowChar, char highChar)
{
return IsNCNameSurrogateChar(lowChar, highChar);
}
#endif
public bool IsStartNameSingleChar(char ch)
{
return IsStartNCNameSingleChar(ch) || ch == ':';
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsCharData(char ch)
{
return (charProperties[ch] & fCharData) != 0;
}
// [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
public bool IsPubidChar(char ch)
{
if (ch < (char)0x80)
{
return (s_PublicIdBitmap[ch >> 4] & (1 << (ch & 0xF))) != 0;
}
return false;
}
// TextChar = CharData - { 0xA, 0xD, '<', '&', ']' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsTextChar(char ch)
{
return (charProperties[ch] & fText) != 0;
}
// AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsAttributeValueChar(char ch)
{
return (charProperties[ch] & fAttrValue) != 0;
}
// XML 1.0 Fourth Edition definitions
//
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsLetter(char ch)
{
return (charProperties[ch] & fLetter) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
// This method uses the XML 4th edition name character ranges
public bool IsNCNameCharXml4e(char ch)
{
return (charProperties[ch] & fNCNameXml4e) != 0;
}
// This method uses the XML 4th edition name character ranges
public bool IsStartNCNameCharXml4e(char ch)
{
return IsLetter(ch) || ch == '_';
}
// This method uses the XML 4th edition name character ranges
public bool IsNameCharXml4e(char ch)
{
return IsNCNameCharXml4e(ch) || ch == ':';
}
// This method uses the XML 4th edition name character ranges
public bool IsStartNameCharXml4e(char ch)
{
return IsStartNCNameCharXml4e(ch) || ch == ':';
}
// Digit methods
public static bool IsDigit(char ch)
{
return InRange(ch, 0x30, 0x39);
}
// Surrogate methods
internal static bool IsHighSurrogate(int ch)
{
return InRange(ch, SurHighStart, SurHighEnd);
}
internal static bool IsLowSurrogate(int ch)
{
return InRange(ch, SurLowStart, SurLowEnd);
}
internal static bool IsSurrogate(int ch)
{
return InRange(ch, SurHighStart, SurLowEnd);
}
internal static int CombineSurrogateChar(int lowChar, int highChar)
{
return (lowChar - SurLowStart) | ((highChar - SurHighStart) << 10) + 0x10000;
}
internal bool IsOnlyWhitespace(string str)
{
return IsOnlyWhitespaceWithPos(str) == -1;
}
// Character checking on strings
internal int IsOnlyWhitespaceWithPos(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fWhitespace) == 0)
{
return i;
}
}
}
return -1;
}
internal int IsOnlyCharData(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fCharData) == 0)
{
if (i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i + 1])))
{
return i;
}
else
{
i++;
}
}
}
}
return -1;
}
internal static bool IsOnlyDigits(string str, int startPos, int len)
{
Debug.Assert(str != null);
Debug.Assert(startPos + len <= str.Length);
Debug.Assert(startPos <= str.Length);
for (int i = startPos; i < startPos + len; i++)
{
if (!IsDigit(str[i]))
{
return false;
}
}
return true;
}
internal int IsPublicId(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if (!IsPubidChar(str[i]))
{
return i;
}
}
}
return -1;
}
// This method tests whether a value is in a given range with just one test; start and end should be constants
private static bool InRange(int value, int start, int end)
{
Debug.Assert(start <= end);
return (uint)(value - start) <= (uint)(end - start);
}
#if XMLCHARTYPE_GEN_RESOURCE
//
// Code for generating XmlCharType.bin table and s_PublicIdBitmap
//
// build command line: csc XmlCharType.cs /d:XMLCHARTYPE_GEN_RESOURCE
//
public static void Main(string[] args)
{
try
{
InitInstance();
// generate PublicId bitmap
ushort[] bitmap = new ushort[0x80 >> 4];
for (int i = 0; i < s_PublicID.Length; i += 2)
{
for (int j = s_PublicID[i], last = s_PublicID[i + 1]; j <= last; j++)
{
bitmap[j >> 4] |= (ushort)(1 << (j & 0xF));
}
}
Console.Write("private const string s_PublicIdBitmap = \"");
for (int i = 0; i < bitmap.Length; i++)
{
Console.Write("\\u{0:x4}", bitmap[i]);
}
Console.WriteLine("\";");
Console.WriteLine();
string fileName = (args.Length == 0) ? "XmlCharType.bin" : args[0];
Console.Write("Writing XmlCharType character properties to {0}...", fileName);
FileStream fs = new FileStream(fileName, FileMode.Create);
for (int i = 0; i < CharPropertiesSize; i += 4096)
{
fs.Write(s_CharProperties, i, 4096);
}
fs.Close();
Console.WriteLine("done.");
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("Exception: {0}", e.Message);
}
}
#endif
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ProgressBar.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Security.Permissions;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Windows.Forms.Layout;
using System.Globalization;
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar"]/*' />
/// <devdoc>
/// <para>
/// Represents a Windows progress bar control.
/// </para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
DefaultProperty("Value"),
DefaultBindingProperty("Value"),
SRDescription(SR.DescriptionProgressBar)
]
public class ProgressBar : Control {
//# VS7 205: simcooke
//REMOVED: AddOnValueChanged, RemoveOnValueChanged, OnValueChanged and all designer plumbing associated with it.
// OnValueChanged event no longer exists.
// these four values define the range of possible values, how to navigate
// through them, and the current position
//
private int minimum = 0;
private int maximum = 100;
private int step = 10;
private int value = 0;
//this defines marquee animation speed
private int marqueeSpeed = 100;
private Color defaultForeColor = SystemColors.Highlight;
private ProgressBarStyle style = ProgressBarStyle.Blocks;
private EventHandler onRightToLeftLayoutChanged;
private bool rightToLeftLayout = false;
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ProgressBar"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.ProgressBar'/> class in its default
/// state.
/// </para>
/// </devdoc>
public ProgressBar()
: base() {
SetStyle(ControlStyles.UserPaint |
ControlStyles.UseTextForAccessibility |
ControlStyles.Selectable, false);
ForeColor = defaultForeColor;
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.CreateParams"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// This is called when creating a window. Inheriting classes can ovveride
/// this to add extra functionality, but should not forget to first call
/// base.getCreateParams() to make sure the control continues to work
/// correctly.
/// </para>
/// </devdoc>
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
cp.ClassName = NativeMethods.WC_PROGRESS;
if (this.Style == ProgressBarStyle.Continuous) {
cp.Style |= NativeMethods.PBS_SMOOTH;
}
else if (this.Style == ProgressBarStyle.Marquee && !DesignMode) {
cp.Style |= NativeMethods.PBS_MARQUEE;
}
if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) {
//We want to turn on mirroring for Form explicitly.
cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL;
//Don't need these styles when mirroring is turned on.
cp.ExStyle &= ~(NativeMethods.WS_EX_RTLREADING | NativeMethods.WS_EX_RIGHT | NativeMethods.WS_EX_LEFTSCROLLBAR);
}
return cp;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.AllowDrop"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override bool AllowDrop {
get {
return base.AllowDrop;
}
set {
base.AllowDrop = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.BackgroundImage"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override Image BackgroundImage {
get {
return base.BackgroundImage;
}
set {
base.BackgroundImage = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Style"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the style of the ProgressBar. This is can be either Blocks or Continuous.
/// </para>
/// </devdoc>
[
Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
DefaultValue(ProgressBarStyle.Blocks),
SRCategory(SR.CatBehavior),
SRDescription(SR.ProgressBarStyleDescr)
]
public ProgressBarStyle Style {
get {
return style;
}
set {
if (style != value) {
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ProgressBarStyle.Blocks, (int)ProgressBarStyle.Marquee)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(ProgressBarStyle));
}
style = value;
if (IsHandleCreated)
RecreateHandle();
if (style == ProgressBarStyle.Marquee)
{
StartMarquee();
}
}
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.BackgroundImageChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler BackgroundImageChanged {
add {
base.BackgroundImageChanged += value;
}
remove {
base.BackgroundImageChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.BackgroundImageLayout"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override ImageLayout BackgroundImageLayout {
get {
return base.BackgroundImageLayout;
}
set {
base.BackgroundImageLayout = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.BackgroundImageLayoutChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler BackgroundImageLayoutChanged {
add {
base.BackgroundImageLayoutChanged += value;
}
remove {
base.BackgroundImageLayoutChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.CausesValidation"]/*' />
/// <internalonly/>
/// <devdoc/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new bool CausesValidation {
get {
return base.CausesValidation;
}
set {
base.CausesValidation = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.CausesValidationChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler CausesValidationChanged {
add {
base.CausesValidationChanged += value;
}
remove {
base.CausesValidationChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.DefaultImeMode"]/*' />
protected override ImeMode DefaultImeMode {
get {
return ImeMode.Disable;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(100, 23);
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.DoubleBuffered"]/*' />
/// <devdoc>
/// This property is overridden and hidden from statement completion
/// on controls that are based on Win32 Native Controls.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
protected override bool DoubleBuffered {
get {
return base.DoubleBuffered;
}
set {
base.DoubleBuffered = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Font"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the font of text in the <see cref='System.Windows.Forms.ProgressBar'/>.
/// </para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override Font Font {
get {
return base.Font;
}
set {
base.Font = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.FontChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler FontChanged {
add {
base.FontChanged += value;
}
remove {
base.FontChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ImeMode"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public ImeMode ImeMode {
get {
return base.ImeMode;
}
set {
base.ImeMode = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ImeModeChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler ImeModeChanged {
add {
base.ImeModeChanged += value;
}
remove {
base.ImeModeChanged -= value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the marquee animation speed of the <see cref='System.Windows.Forms.ProgressBar'/>.
/// Sets the value to a positive number causes the progressBar to move, while setting it to 0
/// stops the progressBar.
/// </para>
/// </devdoc>
[
DefaultValue(100),
SRCategory(SR.CatBehavior),
SRDescription(SR.ProgressBarMarqueeAnimationSpeed)]
public int MarqueeAnimationSpeed {
get {
return marqueeSpeed;
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
set {
if (value < 0) {
throw new ArgumentOutOfRangeException("MarqueeAnimationSpeed must be non-negative");
}
marqueeSpeed = value;
if (!DesignMode) {
StartMarquee();
}
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Maximum"]/*' />
/// <devdoc>
/// <para>
/// Start the Marquee rolling (or stop it, if the speed = 0)
/// </para>
/// </devdoc>
private void StartMarquee()
{
if (IsHandleCreated && style == ProgressBarStyle.Marquee)
{
if (marqueeSpeed == 0)
{
SendMessage(NativeMethods.PBM_SETMARQUEE, 0, marqueeSpeed);
}
else
{
SendMessage(NativeMethods.PBM_SETMARQUEE, 1, marqueeSpeed);
}
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Maximum"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the maximum value of the <see cref='System.Windows.Forms.ProgressBar'/>.
/// Gets or sets the maximum value of the <see cref='System.Windows.Forms.ProgressBar'/>.
/// </para>
/// </devdoc>
[
DefaultValue(100),
SRCategory(SR.CatBehavior),
RefreshProperties(RefreshProperties.Repaint),
SRDescription(SR.ProgressBarMaximumDescr)
]
public int Maximum {
get {
return maximum;
}
set {
if (maximum != value) {
// Ensure that value is in the Win32 control's acceptable range
// Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2.
// Should this set a boundary for the top end too?
if (value < 0)
throw new ArgumentOutOfRangeException("Maximum", SR.GetString(SR.InvalidLowBoundArgumentEx, "Maximum", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
if (minimum > value) minimum = value;
maximum = value;
if (this.value > maximum) this.value = maximum;
if (IsHandleCreated) {
SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum);
UpdatePos() ;
}
}
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Minimum"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the minimum value of the <see cref='System.Windows.Forms.ProgressBar'/>.
/// </para>
/// </devdoc>
[
DefaultValue(0),
SRCategory(SR.CatBehavior),
RefreshProperties(RefreshProperties.Repaint),
SRDescription(SR.ProgressBarMinimumDescr)
]
public int Minimum {
get {
return minimum;
}
set {
if (minimum != value) {
// Ensure that value is in the Win32 control's acceptable range
// Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2.
// Should this set a boundary for the top end too?
if (value < 0)
throw new ArgumentOutOfRangeException("Minimum", SR.GetString(SR.InvalidLowBoundArgumentEx, "Minimum", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
if (maximum < value) maximum = value;
minimum = value;
if (this.value < minimum) this.value = minimum;
if (IsHandleCreated) {
SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum);
UpdatePos() ;
}
}
}
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged(e);
if (IsHandleCreated)
{
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor));
}
}
protected override void OnForeColorChanged(EventArgs e)
{
base.OnForeColorChanged(e);
if (IsHandleCreated)
{
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor));
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Padding"]/*' />
/// <devdoc>
/// <para>
/// <para>[To be supplied.]</para>
/// </para>
/// </devdoc>
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Padding Padding {
get { return base.Padding; }
set { base.Padding = value;}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public new event EventHandler PaddingChanged {
add { base.PaddingChanged += value; }
remove { base.PaddingChanged -= value; }
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.RightToLeftLayout"]/*' />
/// <devdoc>
/// This is used for international applications where the language
/// is written from RightToLeft. When this property is true,
// and the RightToLeft is true, mirroring will be turned on on the form, and
/// control placement and text will be from right to left.
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
DefaultValue(false),
SRDescription(SR.ControlRightToLeftLayoutDescr)
]
public virtual bool RightToLeftLayout {
get {
return rightToLeftLayout;
}
set {
if (value != rightToLeftLayout) {
rightToLeftLayout = value;
using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) {
OnRightToLeftLayoutChanged(EventArgs.Empty);
}
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.RightToLeftLayoutChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnRightToLeftLayoutChangedDescr)]
public event EventHandler RightToLeftLayoutChanged {
add {
onRightToLeftLayoutChanged += value;
}
remove {
onRightToLeftLayoutChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Step"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the amount that a call to <see cref='System.Windows.Forms.ProgressBar.PerformStep'/>
/// increases the progress bar's current position.
/// </para>
/// </devdoc>
[
DefaultValue(10),
SRCategory(SR.CatBehavior),
SRDescription(SR.ProgressBarStepDescr)
]
public int Step {
get {
return step;
}
set {
step = value;
if (IsHandleCreated) SendMessage(NativeMethods.PBM_SETSTEP, step, 0);
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.TabStop"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public bool TabStop {
get {
return base.TabStop;
}
set {
base.TabStop = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.TabStopChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TabStopChanged {
add {
base.TabStopChanged += value;
}
remove {
base.TabStopChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Text"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)]
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.TextChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TextChanged {
add {
base.TextChanged += value;
}
remove {
base.TextChanged -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Value"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the current position of the <see cref='System.Windows.Forms.ProgressBar'/>.
/// </para>
/// </devdoc>
[
DefaultValue(0),
SRCategory(SR.CatBehavior),
Bindable(true),
SRDescription(SR.ProgressBarValueDescr)
]
public int Value {
get {
return value;
}
set {
if (this.value != value) {
if ((value < minimum) || (value > maximum))
throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", value.ToString(CultureInfo.CurrentCulture), "'minimum'", "'maximum'"));
this.value = value;
UpdatePos() ;
}
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.DoubleClick"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler DoubleClick {
add {
base.DoubleClick += value;
}
remove {
base.DoubleClick -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.MouseDoubleClick"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event MouseEventHandler MouseDoubleClick {
add {
base.MouseDoubleClick += value;
}
remove {
base.MouseDoubleClick -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.KeyUp"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyEventHandler KeyUp {
add {
base.KeyUp += value;
}
remove {
base.KeyUp -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.KeyDown"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyEventHandler KeyDown {
add {
base.KeyDown += value;
}
remove {
base.KeyDown -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.KeyPress"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyPressEventHandler KeyPress {
add {
base.KeyPress += value;
}
remove {
base.KeyPress -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Enter"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler Enter {
add {
base.Enter += value;
}
remove {
base.Enter -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Leave"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler Leave {
add {
base.Leave += value;
}
remove {
base.Leave -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.OnPaint"]/*' />
/// <devdoc>
/// ProgressBar Onpaint.
/// </devdoc>
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event PaintEventHandler Paint {
add {
base.Paint += value;
}
remove {
base.Paint -= value;
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.CreateHandle"]/*' />
/// <devdoc>
/// </devdoc>
/// <internalonly/>
protected override void CreateHandle() {
if (!RecreatingHandle) {
IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate();
try {
NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX();
icc.dwICC = NativeMethods.ICC_PROGRESS_CLASS;
SafeNativeMethods.InitCommonControlsEx(icc);
}
finally {
UnsafeNativeMethods.ThemingScope.Deactivate(userCookie);
}
}
base.CreateHandle();
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.Increment"]/*' />
/// <devdoc>
/// <para>
/// Advances the current position of the <see cref='System.Windows.Forms.ProgressBar'/> by the
/// specified increment and redraws the control to reflect the new position.
/// </para>
/// </devdoc>
public void Increment(int value) {
if (this.Style == ProgressBarStyle.Marquee) {
throw new InvalidOperationException(SR.GetString(SR.ProgressBarIncrementMarqueeException));
}
this.value += value;
// Enforce that value is within the range (minimum, maximum)
if (this.value < minimum) {
this.value = minimum;
}
if (this.value > maximum) {
this.value = maximum;
}
UpdatePos();
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.OnHandleCreated"]/*' />
/// <devdoc>
/// Overridden to set up our properties.
/// </devdoc>
/// <internalonly/>
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum);
SendMessage(NativeMethods.PBM_SETSTEP, step, 0);
SendMessage(NativeMethods.PBM_SETPOS, value, 0);
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor));
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor));
StartMarquee();
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChangedHandler);
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.OnHandleDestroyed"]/*' />
/// <devdoc>
/// Overridden to remove event handler.
/// </devdoc>
/// <internalonly/>
protected override void OnHandleDestroyed(EventArgs e)
{
SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(UserPreferenceChangedHandler);
base.OnHandleDestroyed(e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnRightToLeftLayoutChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnRightToLeftLayoutChanged(EventArgs e) {
if (GetAnyDisposingInHierarchy()) {
return;
}
if (RightToLeft == RightToLeft.Yes) {
RecreateHandle();
}
if (onRightToLeftLayoutChanged != null) {
onRightToLeftLayoutChanged(this, e);
}
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.PerformStep"]/*' />
/// <devdoc>
/// <para>
/// Advances the current position of the <see cref='System.Windows.Forms.ProgressBar'/>
/// by the amount of the <see cref='System.Windows.Forms.ProgressBar.Step'/>
/// property, and redraws the control to reflect the new position.
/// </para>
/// </devdoc>
public void PerformStep() {
if (this.Style == ProgressBarStyle.Marquee) {
throw new InvalidOperationException(SR.GetString(SR.ProgressBarPerformStepMarqueeException));
}
Increment(step);
}
/// <include file='doc\Control.uex' path='docs/doc[@for="Control.ResetForeColor"]/*' />
/// <devdoc>
/// Resets the fore color to be based on the parent's fore color.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ResetForeColor() {
ForeColor = defaultForeColor;
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ShouldSerializeForeColor"]/*' />
/// <devdoc>
/// Returns true if the ForeColor should be persisted in code gen.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
internal override bool ShouldSerializeForeColor() {
return ForeColor != defaultForeColor;
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ToString"]/*' />
/// <devdoc>
/// Returns a string representation for this control.
/// </devdoc>
/// <internalonly/>
public override string ToString() {
string s = base.ToString();
return s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + Value.ToString(CultureInfo.CurrentCulture);
}
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.UpdatePos"]/*' />
/// <devdoc>
/// Sends the underlying window a PBM_SETPOS message to update
/// the current value of the progressbar.
/// </devdoc>
/// <internalonly/>
private void UpdatePos() {
if (IsHandleCreated) SendMessage(NativeMethods.PBM_SETPOS, value, 0);
}
//Note: ProgressBar doesn't work like other controls as far as setting ForeColor/
//BackColor -- you need to send messages to update the colors
private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventArgs e)
{
if (IsHandleCreated)
{
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor));
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor));
}
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Cassandra.Connections;
using Cassandra.MetadataHelpers;
namespace Cassandra
{
internal class TokenMap : IReadOnlyTokenMap
{
internal readonly TokenFactory Factory;
// should be IReadOnly but BinarySearch method is not exposed in the interface
private readonly List<IToken> _ring;
private readonly IReadOnlyDictionary<IToken, Host> _primaryReplicas;
private readonly IReadOnlyDictionary<string, DatacenterInfo> _datacenters;
private readonly int _numberOfHostsWithTokens;
private readonly ConcurrentDictionary<string, IReadOnlyDictionary<IToken, ISet<Host>>> _tokenToHostsByKeyspace;
private readonly ConcurrentDictionary<IReplicationStrategy, IReadOnlyDictionary<IToken, ISet<Host>>> _keyspaceTokensCache;
private static readonly Logger Logger = new Logger(typeof(ControlConnection));
internal TokenMap(
TokenFactory factory,
IReadOnlyDictionary<string, IReadOnlyDictionary<IToken, ISet<Host>>> tokenToHostsByKeyspace,
List<IToken> ring,
IReadOnlyDictionary<IToken, Host> primaryReplicas,
IReadOnlyDictionary<IReplicationStrategy, IReadOnlyDictionary<IToken, ISet<Host>>> keyspaceTokensCache,
IReadOnlyDictionary<string, DatacenterInfo> datacenters,
int numberOfHostsWithTokens)
{
Factory = factory;
_tokenToHostsByKeyspace = new ConcurrentDictionary<string, IReadOnlyDictionary<IToken, ISet<Host>>>(tokenToHostsByKeyspace);
_ring = ring;
_primaryReplicas = primaryReplicas;
_keyspaceTokensCache = new ConcurrentDictionary<IReplicationStrategy, IReadOnlyDictionary<IToken, ISet<Host>>>(keyspaceTokensCache);
_datacenters = datacenters;
_numberOfHostsWithTokens = numberOfHostsWithTokens;
}
public IReadOnlyDictionary<IToken, ISet<Host>> GetByKeyspace(string keyspaceName)
{
_tokenToHostsByKeyspace.TryGetValue(keyspaceName, out var value);
return value;
}
public void UpdateKeyspace(KeyspaceMetadata ks)
{
var sw = new Stopwatch();
sw.Start();
TokenMap.UpdateKeyspace(
ks, _tokenToHostsByKeyspace, _ring, _primaryReplicas, _keyspaceTokensCache, _datacenters, _numberOfHostsWithTokens);
sw.Stop();
TokenMap.Logger.Info(
"Finished updating TokenMap for the '{0}' keyspace. It took {1:0} milliseconds.",
ks.Name,
sw.Elapsed.TotalMilliseconds);
}
public ICollection<Host> GetReplicas(string keyspaceName, IToken token)
{
IReadOnlyList<IToken> readOnlyRing = _ring;
// Find the primary replica
var i = _ring.BinarySearch(token);
if (i < 0)
{
//no exact match, use closest index
i = ~i;
if (i >= readOnlyRing.Count)
{
i = 0;
}
}
var closestToken = readOnlyRing[i];
if (keyspaceName != null && _tokenToHostsByKeyspace.ContainsKey(keyspaceName))
{
return _tokenToHostsByKeyspace[keyspaceName][closestToken];
}
TokenMap.Logger.Warning("An attempt to obtain the replicas for a specific token was made but the replicas collection " +
"wasn't computed for this keyspace: {0}. Returning the primary replica for the provided token.", keyspaceName);
return new[] { _primaryReplicas[closestToken] };
}
public static TokenMap Build(string partitioner, ICollection<Host> hosts, ICollection<KeyspaceMetadata> keyspaces)
{
var sw = new Stopwatch();
sw.Start();
var factory = TokenFactory.GetFactory(partitioner);
if (factory == null)
{
return null;
}
var primaryReplicas = new Dictionary<IToken, Host>();
var allSorted = new SortedSet<IToken>();
var datacenters = new Dictionary<string, DatacenterInfo>();
foreach (var host in hosts)
{
if (host.Datacenter != null)
{
if (!datacenters.TryGetValue(host.Datacenter, out var dc))
{
datacenters[host.Datacenter] = dc = new DatacenterInfo();
}
dc.HostLength++;
dc.AddRack(host.Rack);
}
foreach (var tokenStr in host.Tokens)
{
try
{
var token = factory.Parse(tokenStr);
allSorted.Add(token);
primaryReplicas[token] = host;
}
catch
{
TokenMap.Logger.Error($"Token {tokenStr} could not be parsed using {partitioner} partitioner implementation");
}
}
}
var ring = new List<IToken>(allSorted);
var tokenToHosts = new Dictionary<string, IReadOnlyDictionary<IToken, ISet<Host>>>(keyspaces.Count);
var ksTokensCache = new Dictionary<IReplicationStrategy, IReadOnlyDictionary<IToken, ISet<Host>>>();
//Only consider nodes that have tokens
var numberOfHostsWithTokens = hosts.Count(h => h.Tokens.Any());
foreach (var ks in keyspaces)
{
TokenMap.UpdateKeyspace(ks, tokenToHosts, ring, primaryReplicas, ksTokensCache, datacenters, numberOfHostsWithTokens);
IReadOnlyDictionary<IToken, ISet<Host>> replicas;
if (ks.Strategy == null)
{
replicas = primaryReplicas.ToDictionary(kv => kv.Key, kv => (ISet<Host>)new HashSet<Host>(new[] { kv.Value }));
}
else if (!ksTokensCache.TryGetValue(ks.Strategy, out replicas))
{
replicas = ks.Strategy.ComputeTokenToReplicaMap(ring, primaryReplicas, numberOfHostsWithTokens, datacenters);
ksTokensCache.Add(ks.Strategy, replicas);
}
tokenToHosts[ks.Name] = replicas;
}
sw.Stop();
TokenMap.Logger.Info(
"Finished building TokenMap for {0} keyspaces and {1} hosts. It took {2:0} milliseconds.",
keyspaces.Count,
hosts.Count,
sw.Elapsed.TotalMilliseconds);
return new TokenMap(factory, tokenToHosts, ring, primaryReplicas, ksTokensCache, datacenters, numberOfHostsWithTokens);
}
private static void UpdateKeyspace(
KeyspaceMetadata ks,
IDictionary<string, IReadOnlyDictionary<IToken, ISet<Host>>> tokenToHostsByKeyspace,
IReadOnlyList<IToken> ring,
IReadOnlyDictionary<IToken, Host> primaryReplicas,
IDictionary<IReplicationStrategy, IReadOnlyDictionary<IToken, ISet<Host>>> keyspaceTokensCache,
IReadOnlyDictionary<string, DatacenterInfo> datacenters,
int numberOfHostsWithTokens)
{
IReadOnlyDictionary<IToken, ISet<Host>> replicas;
if (ks.Strategy == null)
{
replicas = primaryReplicas.ToDictionary(kv => kv.Key, kv => (ISet<Host>)new HashSet<Host>(new[] { kv.Value }));
}
else if (!keyspaceTokensCache.TryGetValue(ks.Strategy, out replicas))
{
replicas = ks.Strategy.ComputeTokenToReplicaMap(ring, primaryReplicas, numberOfHostsWithTokens, datacenters);
keyspaceTokensCache[ks.Strategy] = replicas;
}
tokenToHostsByKeyspace[ks.Name] = replicas;
}
public void RemoveKeyspace(string name)
{
_tokenToHostsByKeyspace.TryRemove(name, out _);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Threading;
using L4p.Common.DumpToLogs;
using L4p.Common.IoCs;
using L4p.Common.Json;
using L4p.Common.Loggers;
using L4p.Common.PubSub.client.Io;
namespace L4p.Common.PubSub.client
{
interface IMessangerEngine : IHaveDump
{
void SendHelloMsg(comm.HelloMsg msg);
void SendGoodbyeMsg(string agentUri);
void SendPublishMsg(string agentUri, comm.PublishMsg msg);
void FilterTopicMsgs(string agentUri, comm.TopicFilterMsg msg);
void AgentIsHere(string agentUri);
void AgentIsGone(string agentUri);
void IoFailed(IAgentWriter proxy, comm.IoMsg msg, Exception ex, string at);
void Idle();
}
class MessangerEngine : IMessangerEngine
{
#region counters
class Counters
{
public int HelloMsgSent;
public int GoodbyeMsgSent;
public int PublishMsgSent;
public int FilterTopicMsgSent;
public int HeartbeatMsgSent;
public int HubMsgSent;
public int HubMsgFailed;
public int MsgIoFailed;
public int PermanentIoFailures;
public int IoRetry;
}
#endregion
#region members
private static readonly comm.HeartbeatMsg _heartbeatMsg = new comm.HeartbeatMsg();
private readonly Counters _counters;
private readonly string _hubUri;
private readonly ILogFile _log;
private readonly ISignalsConfigRa _configRa;
private readonly IAgentConnector _connector;
private readonly IAgentsRepo _agents;
private readonly SignalsConfig _cachedConfig;
#endregion
#region construction
public static IMessangerEngine New(IIoC ioc)
{
return
new MessangerEngine(ioc);
}
private MessangerEngine(IIoC ioc)
{
_counters = new Counters();
_configRa = ioc.Resolve<ISignalsConfigRa>();
var config = _configRa.Values;
_cachedConfig = config;
_log = ThrottledLog.NewSync(config.ThrottledLogTtl, ioc.Resolve<ILogFile>());
_hubUri = _configRa.MakeHubUri();
_connector = ioc.Resolve<IAgentConnector>();
_agents = AgentsRepo.NewSync();
}
#endregion
#region private
private void set_agent_proxy(string uri, IAgentWriter proxy)
{
var prev = _agents.SetAgentProxy(uri, proxy);
if (prev == null)
return;
_connector.DisconnectAgent(prev);
}
private IAgentWriter get_agent_proxy(string agentUri)
{
var proxy = _agents.GetAgentProxy(agentUri);
if (proxy != null)
return proxy;
proxy = _connector.ConnectAgent(agentUri, this);
set_agent_proxy(agentUri, proxy);
return proxy;
}
private comm.ISignalsHub create_hub_proxy(string uri)
{
var proxy = wcf.SignalsHub.New(uri);
return proxy;
}
private void send_message(string agentUri, string tag, Action action)
{
try
{
action();
Interlocked.Increment(ref _counters.HubMsgSent);
}
catch (Exception ex)
{
_log.Error(ex, "Failure while sending message '{0}' to '{1}'", tag, agentUri);
Interlocked.Increment(ref _counters.HubMsgFailed);
}
}
private void retry_io(comm.IoMsg msg)
{
var retryIt = msg.Retry;
for (;;) // do only once
{
if (retryIt == null)
break;
if (msg.RetryCount == 0)
break;
Interlocked.Increment(ref _counters.IoRetry);
msg.RetryCount--;
retryIt();
return;
}
Interlocked.Increment(ref _counters.PermanentIoFailures);
}
#endregion
#region interface
void IMessangerEngine.SendHelloMsg(comm.HelloMsg msg)
{
using (var hub = create_hub_proxy(_hubUri))
{
send_message(_hubUri, "client.hello",
() => hub.Hello(msg));
}
Interlocked.Increment(ref _counters.HelloMsgSent);
}
void IMessangerEngine.SendGoodbyeMsg(string agentUri)
{
using (var hub = create_hub_proxy(_hubUri))
{
send_message(_hubUri, "client.goodbye",
() => hub.Goodbye(agentUri));
}
Interlocked.Increment(ref _counters.GoodbyeMsgSent);
}
void IMessangerEngine.SendPublishMsg(string agentUri, comm.PublishMsg msg)
{
Action sendIt = () => {
var proxy = get_agent_proxy(agentUri);
proxy.Publish(msg);
};
msg.Retry = sendIt;
msg.RetryCount = _cachedConfig.Client.PublishRetryCount;
sendIt();
Interlocked.Increment(ref _counters.PublishMsgSent);
}
void IMessangerEngine.FilterTopicMsgs(string agentUri, comm.TopicFilterMsg msg)
{
var proxy = get_agent_proxy(agentUri);
proxy.FilterTopicMsgs(msg);
Interlocked.Increment(ref _counters.FilterTopicMsgSent);
}
void IMessangerEngine.AgentIsHere(string agentUri)
{
var proxy = get_agent_proxy(agentUri);
proxy.Heartbeat(_heartbeatMsg);
Interlocked.Increment(ref _counters.HeartbeatMsgSent);
}
void IMessangerEngine.AgentIsGone(string agentUri)
{
var proxy = _agents.RemoveAgent(agentUri);
if (proxy == null)
return;
_connector.DisconnectAgent(proxy);
}
void IMessangerEngine.IoFailed(IAgentWriter proxy, comm.IoMsg msg, Exception ex, string at)
{
Interlocked.Increment(ref _counters.MsgIoFailed);
var msgType = msg.GetType().Name;
_log.Error(ex, "Io error in '{3}' (retryCount={4}) sending '{0}' message to '{1}' (agent will be reconnected); {2}",
msg.AgentUri, msgType, msg.ToJson(), at, msg.RetryCount);
var removedAgent = _agents.RemoveAgent(proxy);
if (removedAgent == null)
return;
_connector.DisconnectAgent(removedAgent);
retry_io(msg);
}
void IMessangerEngine.Idle()
{
var config = _configRa.Values;
var proxies = _agents.GetAll();
foreach (var proxy in proxies)
{
if (proxy.NonActiveSpan < config.Client.HeartbeatSpan)
continue;
proxy.Heartbeat(_heartbeatMsg);
Interlocked.Increment(ref _counters.HeartbeatMsgSent);
}
}
ExpandoObject IHaveDump.Dump(dynamic root)
{
if (root == null)
root = new ExpandoObject();
root.HubUri = _hubUri;
root.Counters = _counters;
var agents = _agents.GetAll();
var list = new List<object>();
foreach (var proxy in agents)
{
list.Add(proxy.Dump());
}
root.Agents = list.ToArray();
return root;
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Lucene.Net.Index;
using Directory = Lucene.Net.Store.Directory;
using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory;
using English = Lucene.Net.Util.English;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
[TestFixture]
public class TestTermVectors:LuceneTestCase
{
private IndexSearcher searcher;
private Directory directory = new MockRAMDirectory();
[SetUp]
public override void SetUp()
{
base.SetUp();
IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
//writer.setUseCompoundFile(true);
//writer.infoStream = System.out;
for (int i = 0; i < 1000; i++)
{
Document doc = new Document();
Field.TermVector termVector;
int mod3 = i % 3;
int mod2 = i % 2;
if (mod2 == 0 && mod3 == 0)
{
termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
}
else if (mod2 == 0)
{
termVector = Field.TermVector.WITH_POSITIONS;
}
else if (mod3 == 0)
{
termVector = Field.TermVector.WITH_OFFSETS;
}
else
{
termVector = Field.TermVector.YES;
}
doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED, termVector));
writer.AddDocument(doc);
}
writer.Close();
searcher = new IndexSearcher(directory, true);
}
[Test]
public virtual void Test()
{
Assert.IsTrue(searcher != null);
}
[Test]
public virtual void TestTermVectors_Renamed()
{
Query query = new TermQuery(new Term("field", "seventy"));
try
{
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(100, hits.Length);
for (int i = 0; i < hits.Length; i++)
{
ITermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].Doc);
Assert.IsTrue(vector != null);
Assert.IsTrue(vector.Length == 1);
}
}
catch (System.IO.IOException)
{
Assert.IsTrue(false);
}
}
[Test]
public virtual void TestTermVectorsFieldOrder()
{
Directory dir = new MockRAMDirectory();
IndexWriter writer = new IndexWriter(dir, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.Add(new Field("c", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("a", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("b", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("x", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(doc);
writer.Close();
IndexReader reader = IndexReader.Open(dir, true);
ITermFreqVector[] v = reader.GetTermFreqVectors(0);
Assert.AreEqual(4, v.Length);
System.String[] expectedFields = new System.String[]{"a", "b", "c", "x"};
int[] expectedPositions = new int[]{1, 2, 0};
for (int i = 0; i < v.Length; i++)
{
TermPositionVector posVec = (TermPositionVector) v[i];
Assert.AreEqual(expectedFields[i], posVec.Field);
System.String[] terms = posVec.GetTerms();
Assert.AreEqual(3, terms.Length);
Assert.AreEqual("content", terms[0]);
Assert.AreEqual("here", terms[1]);
Assert.AreEqual("some", terms[2]);
for (int j = 0; j < 3; j++)
{
int[] positions = posVec.GetTermPositions(j);
Assert.AreEqual(1, positions.Length);
Assert.AreEqual(expectedPositions[j], positions[0]);
}
}
}
[Test]
public virtual void TestTermPositionVectors()
{
Query query = new TermQuery(new Term("field", "zero"));
try
{
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
for (int i = 0; i < hits.Length; i++)
{
ITermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].Doc);
Assert.IsTrue(vector != null);
Assert.IsTrue(vector.Length == 1);
bool shouldBePosVector = (hits[i].Doc % 2 == 0)?true:false;
Assert.IsTrue((shouldBePosVector == false) || (shouldBePosVector == true && (vector[0] is TermPositionVector == true)));
bool shouldBeOffVector = (hits[i].Doc % 3 == 0)?true:false;
Assert.IsTrue((shouldBeOffVector == false) || (shouldBeOffVector == true && (vector[0] is TermPositionVector == true)));
if (shouldBePosVector || shouldBeOffVector)
{
TermPositionVector posVec = (TermPositionVector) vector[0];
System.String[] terms = posVec.GetTerms();
Assert.IsTrue(terms != null && terms.Length > 0);
for (int j = 0; j < terms.Length; j++)
{
int[] positions = posVec.GetTermPositions(j);
TermVectorOffsetInfo[] offsets = posVec.GetOffsets(j);
if (shouldBePosVector)
{
Assert.IsTrue(positions != null);
Assert.IsTrue(positions.Length > 0);
}
else
Assert.IsTrue(positions == null);
if (shouldBeOffVector)
{
Assert.IsTrue(offsets != null);
Assert.IsTrue(offsets.Length > 0);
}
else
Assert.IsTrue(offsets == null);
}
}
else
{
try
{
TermPositionVector posVec = (TermPositionVector) vector[0];
Assert.IsTrue(false);
}
catch (System.InvalidCastException ignore)
{
ITermFreqVector freqVec = vector[0];
System.String[] terms = freqVec.GetTerms();
Assert.IsTrue(terms != null && terms.Length > 0);
}
}
}
}
catch (System.IO.IOException)
{
Assert.IsTrue(false);
}
}
[Test]
public virtual void TestTermOffsetVectors()
{
Query query = new TermQuery(new Term("field", "fifty"));
try
{
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(100, hits.Length);
for (int i = 0; i < hits.Length; i++)
{
ITermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].Doc);
Assert.IsTrue(vector != null);
Assert.IsTrue(vector.Length == 1);
//Assert.IsTrue();
}
}
catch (System.IO.IOException)
{
Assert.IsTrue(false);
}
}
[Test]
public virtual void TestKnownSetOfDocuments()
{
System.String test1 = "eating chocolate in a computer lab"; //6 terms
System.String test2 = "computer in a computer lab"; //5 terms
System.String test3 = "a chocolate lab grows old"; //5 terms
System.String test4 = "eating chocolate with a chocolate lab in an old chocolate colored computer lab"; //13 terms
System.Collections.IDictionary test4Map = new System.Collections.Hashtable();
test4Map["chocolate"] = 3;
test4Map["lab"] = 2;
test4Map["eating"] = 1;
test4Map["computer"] = 1;
test4Map["with"] = 1;
test4Map["a"] = 1;
test4Map["colored"] = 1;
test4Map["in"] = 1;
test4Map["an"] = 1;
test4Map["computer"] = 1;
test4Map["old"] = 1;
Document testDoc1 = new Document();
SetupDoc(testDoc1, test1);
Document testDoc2 = new Document();
SetupDoc(testDoc2, test2);
Document testDoc3 = new Document();
SetupDoc(testDoc3, test3);
Document testDoc4 = new Document();
SetupDoc(testDoc4, test4);
Directory dir = new MockRAMDirectory();
try
{
IndexWriter writer = new IndexWriter(dir, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
Assert.IsTrue(writer != null);
writer.AddDocument(testDoc1);
writer.AddDocument(testDoc2);
writer.AddDocument(testDoc3);
writer.AddDocument(testDoc4);
writer.Close();
IndexSearcher knownSearcher = new IndexSearcher(dir, true);
TermEnum termEnum = knownSearcher.reader_ForNUnit.Terms();
TermDocs termDocs = knownSearcher.reader_ForNUnit.TermDocs();
//System.out.println("Terms: " + termEnum.size() + " Orig Len: " + termArray.length);
Similarity sim = knownSearcher.Similarity;
while (termEnum.Next() == true)
{
Term term = termEnum.Term;
//System.out.println("Term: " + term);
termDocs.Seek(term);
while (termDocs.Next())
{
int docId = termDocs.Doc;
int freq = termDocs.Freq;
//System.out.println("Doc Id: " + docId + " freq " + freq);
ITermFreqVector vector = knownSearcher.reader_ForNUnit.GetTermFreqVector(docId, "field");
float tf = sim.Tf(freq);
float idf = sim.Idf(knownSearcher.DocFreq(term), knownSearcher.MaxDoc);
//float qNorm = sim.queryNorm()
//This is fine since we don't have stop words
float lNorm = sim.LengthNorm("field", vector.GetTerms().Length);
//float coord = sim.coord()
//System.out.println("TF: " + tf + " IDF: " + idf + " LenNorm: " + lNorm);
Assert.IsTrue(vector != null);
System.String[] vTerms = vector.GetTerms();
int[] freqs = vector.GetTermFrequencies();
for (int i = 0; i < vTerms.Length; i++)
{
if (term.Text.Equals(vTerms[i]))
{
Assert.IsTrue(freqs[i] == freq);
}
}
}
//System.out.println("--------");
}
Query query = new TermQuery(new Term("field", "chocolate"));
ScoreDoc[] hits = knownSearcher.Search(query, null, 1000).ScoreDocs;
//doc 3 should be the first hit b/c it is the shortest match
Assert.IsTrue(hits.Length == 3);
float score = hits[0].Score;
/*System.out.println("Hit 0: " + hits.id(0) + " Score: " + hits.score(0) + " String: " + hits.doc(0).toString());
System.out.println("Explain: " + knownSearcher.explain(query, hits.id(0)));
System.out.println("Hit 1: " + hits.id(1) + " Score: " + hits.score(1) + " String: " + hits.doc(1).toString());
System.out.println("Explain: " + knownSearcher.explain(query, hits.id(1)));
System.out.println("Hit 2: " + hits.id(2) + " Score: " + hits.score(2) + " String: " + hits.doc(2).toString());
System.out.println("Explain: " + knownSearcher.explain(query, hits.id(2)));*/
Assert.IsTrue(hits[0].Doc == 2);
Assert.IsTrue(hits[1].Doc == 3);
Assert.IsTrue(hits[2].Doc == 0);
ITermFreqVector vector2 = knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].Doc, "field");
Assert.IsTrue(vector2 != null);
//System.out.println("Vector: " + vector);
System.String[] terms = vector2.GetTerms();
int[] freqs2 = vector2.GetTermFrequencies();
Assert.IsTrue(terms != null && terms.Length == 10);
for (int i = 0; i < terms.Length; i++)
{
System.String term = terms[i];
//System.out.println("Term: " + term);
int freq = freqs2[i];
Assert.IsTrue(test4.IndexOf(term) != - 1);
System.Int32 freqInt = -1;
try
{
freqInt = (System.Int32) test4Map[term];
}
catch (Exception)
{
Assert.IsTrue(false);
}
Assert.IsTrue(freqInt == freq);
}
SortedTermVectorMapper mapper = new SortedTermVectorMapper(new TermVectorEntryFreqSortedComparator());
knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].Doc, mapper);
var vectorEntrySet = mapper.TermVectorEntrySet;
Assert.IsTrue(vectorEntrySet.Count == 10, "mapper.getTermVectorEntrySet() Size: " + vectorEntrySet.Count + " is not: " + 10);
TermVectorEntry last = null;
foreach(TermVectorEntry tve in vectorEntrySet)
{
if (tve != null && last != null)
{
Assert.IsTrue(last.Frequency >= tve.Frequency, "terms are not properly sorted");
System.Int32 expectedFreq = (System.Int32) test4Map[tve.Term];
//we expect double the expectedFreq, since there are two fields with the exact same text and we are collapsing all fields
Assert.IsTrue(tve.Frequency == 2 * expectedFreq, "Frequency is not correct:");
}
last = tve;
}
FieldSortedTermVectorMapper fieldMapper = new FieldSortedTermVectorMapper(new TermVectorEntryFreqSortedComparator());
knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].Doc, fieldMapper);
var map = fieldMapper.FieldToTerms;
Assert.IsTrue(map.Count == 2, "map Size: " + map.Count + " is not: " + 2);
vectorEntrySet = map["field"];
Assert.IsTrue(vectorEntrySet != null, "vectorEntrySet is null and it shouldn't be");
Assert.IsTrue(vectorEntrySet.Count == 10, "vectorEntrySet Size: " + vectorEntrySet.Count + " is not: " + 10);
knownSearcher.Close();
}
catch (System.IO.IOException e)
{
System.Console.Error.WriteLine(e.StackTrace);
Assert.IsTrue(false);
}
}
private void SetupDoc(Document doc, System.String text)
{
doc.Add(new Field("field2", text, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("field", text, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
//System.out.println("Document: " + doc);
}
// Test only a few docs having vectors
[Test]
public virtual void TestRareVectors()
{
IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < 100; i++)
{
Document doc = new Document();
doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
writer.AddDocument(doc);
}
for (int i = 0; i < 10; i++)
{
Document doc = new Document();
doc.Add(new Field("field", English.IntToEnglish(100 + i), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(doc);
}
writer.Close();
searcher = new IndexSearcher(directory, true);
Query query = new TermQuery(new Term("field", "hundred"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(10, hits.Length);
for (int i = 0; i < hits.Length; i++)
{
ITermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].Doc);
Assert.IsTrue(vector != null);
Assert.IsTrue(vector.Length == 1);
}
}
// In a single doc, for the same field, mix the term
// vectors up
[Test]
public virtual void TestMixedVectrosVectors()
{
IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(doc);
writer.Close();
searcher = new IndexSearcher(directory, true);
Query query = new TermQuery(new Term("field", "one"));
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
ITermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[0].Doc);
Assert.IsTrue(vector != null);
Assert.IsTrue(vector.Length == 1);
TermPositionVector tfv = (TermPositionVector) vector[0];
Assert.IsTrue(tfv.Field.Equals("field"));
System.String[] terms = tfv.GetTerms();
Assert.AreEqual(1, terms.Length);
Assert.AreEqual(terms[0], "one");
Assert.AreEqual(5, tfv.GetTermFrequencies()[0]);
int[] positions = tfv.GetTermPositions(0);
Assert.AreEqual(5, positions.Length);
for (int i = 0; i < 5; i++)
Assert.AreEqual(i, positions[i]);
TermVectorOffsetInfo[] offsets = tfv.GetOffsets(0);
Assert.AreEqual(5, offsets.Length);
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(4 * i, offsets[i].StartOffset);
Assert.AreEqual(4 * i + 3, offsets[i].EndOffset);
}
}
}
}
| |
namespace ControlzEx.Controls
{
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using ControlzEx.Automation.Peers;
using ControlzEx.Internal;
using ControlzEx.Internal.KnownBoxes;
/// <summary>
/// The standard WPF TabControl is quite bad in the fact that it only
/// even contains the current TabItem in the VisualTree, so if you
/// have complex views it takes a while to re-create the view each tab
/// selection change.Which makes the standard TabControl very sticky to
/// work with. This class along with its associated ControlTemplate
/// allow all TabItems to remain in the VisualTree without it being Sticky.
/// It does this by keeping all TabItem content in the VisualTree but
/// hides all inactive TabItem content, and only keeps the active TabItem
/// content shown.
///
/// Acknowledgement
/// Eric Burke
/// http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
/// Sacha Barber: https://sachabarbs.wordpress.com/about-me/
/// http://stackoverflow.com/a/10210889/920384
/// http://stackoverflow.com/a/7838955/920384
/// </summary>
/// <remarks>
/// We use two attached properties to later recognize the content presenters we generated.
/// We need the OwningItem because the TabItem associated with an item can later change.
///
/// We need the OwningTabItem to reduce the amount of lookups we have to do.
/// </remarks>
[TemplatePart(Name = "PART_HeaderPanel", Type = typeof(Panel))]
[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : TabControl
{
private static readonly MethodInfo? updateSelectedContentMethodInfo = typeof(TabControl).GetMethod("UpdateSelectedContent", BindingFlags.NonPublic | BindingFlags.Instance);
private Panel? itemsHolder;
#pragma warning disable WPF0010
/// <summary>Identifies the <see cref="ChildContentVisibility"/> dependency property.</summary>
public static readonly DependencyProperty ChildContentVisibilityProperty
= DependencyProperty.Register(nameof(ChildContentVisibility), typeof(Visibility), typeof(TabControlEx), new PropertyMetadata(VisibilityBoxes.Visible));
/// <summary>Identifies the <see cref="TabPanelVisibility"/> dependency property.</summary>
public static readonly DependencyProperty TabPanelVisibilityProperty =
DependencyProperty.Register(nameof(TabPanelVisibility), typeof(Visibility), typeof(TabControlEx), new PropertyMetadata(VisibilityBoxes.Visible));
#pragma warning restore WPF0010
public static readonly DependencyProperty OwningTabItemProperty = DependencyProperty.RegisterAttached("OwningTabItem", typeof(TabItem), typeof(TabControlEx), new PropertyMetadata(default(TabItem)));
/// <summary>Helper for getting <see cref="OwningTabItemProperty"/> from <paramref name="element"/>.</summary>
/// <param name="element"><see cref="DependencyObject"/> to read <see cref="OwningTabItemProperty"/> from.</param>
/// <returns>OwningTabItem property value.</returns>
[AttachedPropertyBrowsableForType(typeof(ContentPresenter))]
public static TabItem? GetOwningTabItem(DependencyObject element)
{
return (TabItem?)element.GetValue(OwningTabItemProperty);
}
/// <summary>Helper for setting <see cref="OwningTabItemProperty"/> on <paramref name="element"/>.</summary>
/// <param name="element"><see cref="DependencyObject"/> to set <see cref="OwningTabItemProperty"/> on.</param>
/// <param name="value">OwningTabItem property value.</param>
public static void SetOwningTabItem(DependencyObject element, TabItem? value)
{
element.SetValue(OwningTabItemProperty, value);
}
public static readonly DependencyProperty OwningItemProperty = DependencyProperty.RegisterAttached("OwningItem", typeof(object), typeof(TabControlEx), new PropertyMetadata(default(object)));
/// <summary>Helper for setting <see cref="OwningItemProperty"/> on <paramref name="element"/>.</summary>
/// <param name="element"><see cref="DependencyObject"/> to set <see cref="OwningItemProperty"/> on.</param>
/// <param name="value">OwningItem property value.</param>
public static void SetOwningItem(DependencyObject element, object? value)
{
element.SetValue(OwningItemProperty, value);
}
/// <summary>Helper for getting <see cref="OwningItemProperty"/> from <paramref name="element"/>.</summary>
/// <param name="element"><see cref="DependencyObject"/> to read <see cref="OwningItemProperty"/> from.</param>
/// <returns>OwningItem property value.</returns>
[AttachedPropertyBrowsableForType(typeof(ContentPresenter))]
public static object? GetOwningItem(DependencyObject element)
{
return (object?)element.GetValue(OwningItemProperty);
}
/// <summary>Identifies the <see cref="MoveFocusToContentWhenSelectionChanges"/> dependency property.</summary>
public static readonly DependencyProperty MoveFocusToContentWhenSelectionChangesProperty = DependencyProperty.Register(nameof(MoveFocusToContentWhenSelectionChanges), typeof(bool), typeof(TabControlEx), new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// Gets or sets whether keyboard focus should be moved to the content area when the selected item changes.
/// </summary>
public bool MoveFocusToContentWhenSelectionChanges
{
get => (bool)this.GetValue(MoveFocusToContentWhenSelectionChangesProperty);
set => this.SetValue(MoveFocusToContentWhenSelectionChangesProperty, BooleanBoxes.Box(value));
}
static TabControlEx()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TabControlEx), new FrameworkPropertyMetadata(typeof(TabControlEx)));
}
/// <summary>
/// Initializes a new instance.
/// </summary>
public TabControlEx()
{
this.Unloaded += this.HandleTabControlExUnloaded;
}
/// <summary>
/// Defines if the TabPanel (Tab-Header) are visible.
/// </summary>
public Visibility TabPanelVisibility
{
get => (Visibility)this.GetValue(TabPanelVisibilityProperty);
set => this.SetValue(TabPanelVisibilityProperty, VisibilityBoxes.Box(value));
}
/// <summary>
/// Gets or sets the child content visibility.
/// </summary>
/// <value>
/// The child content visibility.
/// </value>
public Visibility ChildContentVisibility
{
get => (Visibility)this.GetValue(ChildContentVisibilityProperty);
set => this.SetValue(ChildContentVisibilityProperty, VisibilityBoxes.Box(value));
}
/// <inheritdoc />
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var newItemsHolder = this.Template.FindName("PART_ItemsHolder", this) as Panel;
var isDifferentItemsHolder = ReferenceEquals(this.itemsHolder, newItemsHolder) == false;
if (isDifferentItemsHolder)
{
this.ClearItemsHolder();
}
this.itemsHolder = newItemsHolder;
if (isDifferentItemsHolder)
{
this.UpdateSelectedContent();
}
}
/// <inheritdoc />
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
this.ItemContainerGenerator.StatusChanged += this.OnGeneratorStatusChanged;
this.ItemContainerGenerator.ItemsChanged += this.OnGeneratorItemsChanged;
}
/// <inheritdoc />
/// <summary>
/// When the items change we remove any generated panel children and add any new ones as necessary.
/// </summary>
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
if (this.itemsHolder is null)
{
return;
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Reset:
this.RefreshItemsHolder();
break;
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
if (e.OldItems is not null)
{
foreach (var item in e.OldItems)
{
var contentPresenter = this.FindChildContentPresenter(item, null);
if (contentPresenter is not null)
{
this.itemsHolder.Children.Remove(contentPresenter);
}
}
}
// don't do anything with new items because we don't want to
// create visuals that aren't being shown yet
this.UpdateSelectedContent();
break;
case NotifyCollectionChangedAction.Replace:
// Replace is not really implemented yet
this.RefreshItemsHolder();
break;
}
}
/// <inheritdoc />
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
// If we don't have an items holder we can safely forward the call to base
if (this.itemsHolder is null)
{
base.OnSelectionChanged(e);
return;
}
// We must NOT call base.OnSelectionChanged because that would interfere with our ability to update the selected content before the automation events are fired etc.
if (FrameworkAppContextSwitches.SelectionPropertiesCanLagBehindSelectionChangedEvent)
{
this.RaiseSelectionChangedEvent(e);
if (this.IsKeyboardFocusWithin)
{
this.GetSelectedTabItem()?.SetFocus();
}
this.UpdateSelectedContent();
}
else
{
var keyboardFocusWithin = this.IsKeyboardFocusWithin;
this.UpdateSelectedContent();
if (keyboardFocusWithin)
{
this.GetSelectedTabItem()?.SetFocus();
}
this.RaiseSelectionChangedEvent(e);
}
if (!AutomationPeer.ListenerExists(AutomationEvents.SelectionPatternOnInvalidated)
&& !AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementSelected)
&& (!AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementAddedToSelection) && !AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection)))
{
return;
}
(UIElementAutomationPeer.CreatePeerForElement(this) as TabControlAutomationPeer)?.RaiseSelectionEvents(e);
}
private void RaiseSelectionChangedEvent(SelectionChangedEventArgs e)
{
this.RaiseEvent(e);
}
/// <inheritdoc />
protected override void OnKeyDown(KeyEventArgs e)
{
// We need this to prevent the base class to always accept CTRL + TAB navigation regardless of which keyboard navigation mode is set for this control
if (e.Key == Key.Tab
&& (e.KeyboardDevice.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
var controlTabNavigation = KeyboardNavigation.GetControlTabNavigation(this);
if (controlTabNavigation != KeyboardNavigationMode.Cycle
&& controlTabNavigation != KeyboardNavigationMode.Continue)
{
return;
}
}
base.OnKeyDown(e);
}
/// <inheritdoc />
protected override AutomationPeer OnCreateAutomationPeer()
{
// If we don't have an items holder we can safely forward the call to base
if (this.itemsHolder is null)
{
return base.OnCreateAutomationPeer();
}
var automationPeer = new TabControlExAutomationPeer(this);
return automationPeer;
}
/// <summary>
/// Copied from <see cref="TabControl"/>. wish it were protected in that class instead of private.
/// </summary>
public TabItem? GetSelectedTabItem()
{
var selectedItem = this.SelectedItem;
if (selectedItem is null)
{
return null;
}
var tabItem = selectedItem as TabItem;
if (tabItem is null)
{
tabItem = this.ItemContainerGenerator.ContainerFromIndex(this.SelectedIndex) as TabItem;
if (tabItem is null
// is this really the container we wanted?
|| ReferenceEquals(selectedItem, this.ItemContainerGenerator.ItemFromContainer(tabItem)) == false)
{
tabItem = this.ItemContainerGenerator.ContainerFromItem(selectedItem) as TabItem;
}
}
return tabItem;
}
private void ClearItemsHolder()
{
if (this.itemsHolder is null)
{
return;
}
foreach (var itemsHolderChild in this.itemsHolder.Children)
{
var contentPresenter = itemsHolderChild as ContentPresenter;
contentPresenter?.ClearValue(OwningItemProperty);
contentPresenter?.ClearValue(OwningTabItemProperty);
}
this.itemsHolder.Children.Clear();
}
/// <summary>
/// Clears all current children by calling <see cref="ClearItemsHolder"/> and calls <see cref="UpdateSelectedContent"/> afterwards.
/// </summary>
private void RefreshItemsHolder()
{
this.ClearItemsHolder();
this.UpdateSelectedContent();
}
private void HandleTabControlExLoaded(object? sender, RoutedEventArgs e)
{
this.Loaded -= this.HandleTabControlExLoaded;
this.UpdateSelectedContent();
}
private void HandleTabControlExUnloaded(object? sender, RoutedEventArgs e)
{
this.Loaded -= this.HandleTabControlExLoaded;
this.Loaded += this.HandleTabControlExLoaded;
this.ClearItemsHolder();
}
private void OnGeneratorStatusChanged(object? sender, EventArgs e)
{
if (this.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
{
return;
}
this.UpdateSelectedContent();
}
private void OnGeneratorItemsChanged(object? sender, ItemsChangedEventArgs e)
{
// We only care about reset.
// Reset, in case of ItemContainerGenerator, is generated when it's refreshed.
// It gets refresh when things like ItemContainerStyleSelector etc. change.
if (e.Action == NotifyCollectionChangedAction.Reset)
{
this.RefreshItemsHolder();
}
}
/// <summary>
/// Generate a ContentPresenter for the selected item and control the visibility of already created presenters.
/// </summary>
private void UpdateSelectedContent()
{
if (this.itemsHolder is null)
{
return;
}
updateSelectedContentMethodInfo?.Invoke(this, null);
var selectedTabItem = this.GetSelectedTabItem();
if (selectedTabItem is not null)
{
// generate a ContentPresenter if necessary
this.CreateChildContentPresenterIfRequired(this.SelectedItem, selectedTabItem);
}
// show the right child
foreach (ContentPresenter? contentPresenter in this.itemsHolder.Children)
{
if (contentPresenter is null)
{
continue;
}
var tabItem = (TabItem?)this.ItemContainerGenerator.ContainerFromItem(GetOwningItem(contentPresenter)) ?? GetOwningTabItem(contentPresenter);
// Hide all non selected items and show the selected item
if (tabItem?.IsSelected == true)
{
contentPresenter.Visibility = Visibility.Visible;
contentPresenter.HorizontalAlignment = tabItem.HorizontalContentAlignment;
contentPresenter.VerticalAlignment = tabItem.VerticalContentAlignment;
if (tabItem.ContentTemplate is null
&& tabItem.ContentTemplateSelector is null
&& tabItem.ContentStringFormat is null)
{
contentPresenter.ContentTemplate = this.ContentTemplate;
contentPresenter.ContentTemplateSelector = this.ContentTemplateSelector;
contentPresenter.ContentStringFormat = this.ContentStringFormat;
}
else
{
contentPresenter.ContentTemplate = tabItem.ContentTemplate;
contentPresenter.ContentTemplateSelector = tabItem.ContentTemplateSelector;
contentPresenter.ContentStringFormat = tabItem.ContentStringFormat;
}
}
else
{
contentPresenter.Visibility = Visibility.Collapsed;
}
if (tabItem is not null
&& this.MoveFocusToContentWhenSelectionChanges)
{
this.MoveFocusToContent(contentPresenter, tabItem);
}
}
}
/// <summary>
/// Create the child ContentPresenter for the given item (could be data or a TabItem) if none exists.
/// </summary>
private void CreateChildContentPresenterIfRequired(object? item, TabItem tabItem)
{
if (item is null)
{
return;
}
// Jump out if we already created a ContentPresenter for this item
if (this.FindChildContentPresenter(item, tabItem) is not null)
{
return;
}
var contentPresenter = this.CreateChildContentPresenter(item, tabItem);
this.itemsHolder?.Children.Add(contentPresenter);
}
protected virtual ContentPresenter CreateChildContentPresenter(object? item, TabItem tabItem)
{
// the actual child to be added
var contentPresenter = new ContentPresenter
{
Content = item is TabItem itemAsTabItem ? itemAsTabItem.Content : item,
Visibility = Visibility.Collapsed
};
var owningTabItem = item as TabItem ?? (TabItem)this.ItemContainerGenerator.ContainerFromItem(item);
if (owningTabItem is null)
{
throw new Exception("No owning TabItem could be found.");
}
SetOwningItem(contentPresenter, item);
SetOwningTabItem(contentPresenter, owningTabItem);
return contentPresenter;
}
/// <summary>
/// Find the <see cref="ContentPresenter"/> for the given object. Data could be a TabItem or a piece of data.
/// </summary>
public ContentPresenter? FindChildContentPresenter(object? item, TabItem? tabItem)
{
if (item is null)
{
return null;
}
if (this.itemsHolder is null)
{
return null;
}
var contentPresenters = this.itemsHolder.Children
.OfType<ContentPresenter>()
.ToList();
if (tabItem is not null)
{
return contentPresenters
.FirstOrDefault(contentPresenter => ReferenceEquals(GetOwningTabItem(contentPresenter), tabItem))
?? contentPresenters
.FirstOrDefault(contentPresenter => ReferenceEquals(GetOwningItem(contentPresenter), item));
}
return contentPresenters
.FirstOrDefault(contentPresenter => ReferenceEquals(GetOwningItem(contentPresenter), item))
?? contentPresenters
.FirstOrDefault(contentPresenter => ReferenceEquals(contentPresenter.Content, item));
}
private void MoveFocusToContent(ContentPresenter contentPresenter, TabItem tabItem)
{
// Do nothing if the item is not visible or already has keyboard focus
if (contentPresenter.Visibility != Visibility.Visible
|| contentPresenter.IsKeyboardFocusWithin)
{
return;
}
var presenter = contentPresenter;
this.Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action)(() =>
{
tabItem.BringIntoView();
presenter.BringIntoView();
if (presenter.IsKeyboardFocusWithin == false)
{
presenter.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
}
}));
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
namespace System.Data.SQLite
{
using sqlite3_int64 = System.Int64;
using sqlite3_stmt = Sqlite3.Vdbe;
internal partial class Sqlite3
{
/*
** 2005 July 8
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code associated with the ANALYZE command.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
#if !SQLITE_OMIT_ANALYZE
//#include "sqliteInt.h"
/*
** This routine generates code that opens the sqlite_stat1 table for
** writing with cursor iStatCur. If the library was built with the
** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
** opened for writing using cursor (iStatCur+1)
**
** If the sqlite_stat1 tables does not previously exist, it is created.
** Similarly, if the sqlite_stat2 table does not exist and the library
** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
**
** Argument zWhere may be a pointer to a buffer containing a table name,
** or it may be a NULL pointer. If it is not NULL, then all entries in
** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
** with the named table are deleted. If zWhere==0, then code is generated
** to delete all stat table entries.
*/
public struct _aTable
{
public string zName;
public string zCols;
public _aTable(string zName, string zCols)
{
this.zName = zName;
this.zCols = zCols;
}
};
static _aTable[] aTable = new _aTable[]{
new _aTable( "sqlite_stat1", "tbl,idx,stat" ),
#if SQLITE_ENABLE_STAT2
new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ),
#endif
};
static void openStatTable(
Parse pParse, /* Parsing context */
int iDb, /* The database we are looking in */
int iStatCur, /* Open the sqlite_stat1 table on this cursor */
string zWhere, /* Delete entries for this table or index */
string zWhereType /* Either "tbl" or "idx" */
)
{
int[] aRoot = new int[] { 0, 0 };
u8[] aCreateTbl = new u8[] { 0, 0 };
int i;
sqlite3 db = pParse.db;
Db pDb;
Vdbe v = sqlite3GetVdbe(pParse);
if (v == null)
return;
Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
Debug.Assert(sqlite3VdbeDb(v) == db);
pDb = db.aDb[iDb];
for (i = 0; i < ArraySize(aTable); i++)
{
string zTab = aTable[i].zName;
Table pStat;
if ((pStat = sqlite3FindTable(db, zTab, pDb.zName)) == null)
{
/* The sqlite_stat[12] table does not exist. Create it. Note that a
** side-effect of the CREATE TABLE statement is to leave the rootpage
** of the new table in register pParse.regRoot. This is important
** because the OpenWrite opcode below will be needing it. */
sqlite3NestedParse(pParse,
"CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols
);
aRoot[i] = pParse.regRoot;
aCreateTbl[i] = 1;
}
else
{
/* The table already exists. If zWhere is not NULL, delete all entries
** associated with the table zWhere. If zWhere is NULL, delete the
** entire contents of the table. */
aRoot[i] = pStat.tnum;
sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
if (!String.IsNullOrEmpty(zWhere))
{
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere
);
}
else
{
/* The sqlite_stat[12] table already exists. Delete all rows. */
sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
}
}
}
/* Open the sqlite_stat[12] tables for writing. */
for (i = 0; i < ArraySize(aTable); i++)
{
sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb);
sqlite3VdbeChangeP4(v, -1, 3, P4_INT32);
sqlite3VdbeChangeP5(v, aCreateTbl[i]);
}
}
/*
** Generate code to do an analysis of all indices associated with
** a single table.
*/
static void analyzeOneTable(
Parse pParse, /* Parser context */
Table pTab, /* Table whose indices are to be analyzed */
Index pOnlyIdx, /* If not NULL, only analyze this one index */
int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
int iMem /* Available memory locations begin here */
)
{
sqlite3 db = pParse.db; /* Database handle */
Index pIdx; /* An index to being analyzed */
int iIdxCur; /* Cursor open on index being analyzed */
Vdbe v; /* The virtual machine being built up */
int i; /* Loop counter */
int topOfLoop; /* The top of the loop */
int endOfLoop; /* The end of the loop */
int jZeroRows = -1; /* Jump from here if number of rows is zero */
int iDb; /* Index of database containing pTab */
int regTabname = iMem++; /* Register containing table name */
int regIdxname = iMem++; /* Register containing index name */
int regSampleno = iMem++; /* Register containing next sample number */
int regCol = iMem++; /* Content of a column analyzed table */
int regRec = iMem++; /* Register holding completed record */
int regTemp = iMem++; /* Temporary use register */
int regRowid = iMem++; /* Rowid for the inserted record */
#if SQLITE_ENABLE_STAT2
int addr = 0; /* Instruction address */
int regTemp2 = iMem++; /* Temporary use register */
int regSamplerecno = iMem++; /* Index of next sample to record */
int regRecno = iMem++; /* Current sample index */
int regLast = iMem++; /* Index of last sample to record */
int regFirst = iMem++; /* Index of first sample to record */
#endif
v = sqlite3GetVdbe(pParse);
if (v == null || NEVER(pTab == null))
{
return;
}
if (pTab.tnum == 0)
{
/* Do not gather statistics on views or virtual tables */
return;
}
if (pTab.zName.StartsWith("sqlite_", StringComparison.InvariantCultureIgnoreCase))
{
/* Do not gather statistics on system tables */
return;
}
Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
Debug.Assert(iDb >= 0);
Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
#if !SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0,
db.aDb[iDb].zName ) ){
return;
}
#endif
/* Establish a read-lock on the table at the shared-cache level. */
sqlite3TableLock(pParse, iDb, pTab.tnum, 0, pTab.zName);
iIdxCur = pParse.nTab++;
sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab.zName, 0);
for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
{
int nCol;
KeyInfo pKey;
if (pOnlyIdx != null && pOnlyIdx != pIdx)
continue;
nCol = pIdx.nColumn;
pKey = sqlite3IndexKeyinfo(pParse, pIdx);
if (iMem + 1 + (nCol * 2) > pParse.nMem)
{
pParse.nMem = iMem + 1 + (nCol * 2);
}
/* Open a cursor to the index to be analyzed. */
Debug.Assert(iDb == sqlite3SchemaToIndex(db, pIdx.pSchema));
sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb,
pKey, P4_KEYINFO_HANDOFF);
VdbeComment(v, "%s", pIdx.zName);
/* Populate the registers containing the index names. */
sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0);
#if SQLITE_ENABLE_STAT2
/* If this iteration of the loop is generating code to analyze the
** first index in the pTab.pIndex list, then register regLast has
** not been populated. In this case populate it now. */
if ( pTab.pIndex == pIdx )
{
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2 - 1, regTemp );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2, regTemp2 );
sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regLast );
sqlite3VdbeAddOp2( v, OP_Null, 0, regFirst );
addr = sqlite3VdbeAddOp3( v, OP_Lt, regSamplerecno, 0, regLast );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regFirst );
sqlite3VdbeAddOp3( v, OP_Multiply, regLast, regTemp, regLast );
sqlite3VdbeAddOp2( v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES * 2 - 2 );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regLast );
sqlite3VdbeJumpHere( v, addr );
}
/* Zero the regSampleno and regRecno registers. */
sqlite3VdbeAddOp2( v, OP_Integer, 0, regSampleno );
sqlite3VdbeAddOp2( v, OP_Integer, 0, regRecno );
sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno );
#endif
/* The block of memory cells initialized here is used as follows.
**
** iMem:
** The total number of rows in the table.
**
** iMem+1 .. iMem+nCol:
** Number of distinct entries in index considering the
** left-most N columns only, where N is between 1 and nCol,
** inclusive.
**
** iMem+nCol+1 .. Mem+2*nCol:
** Previous value of indexed columns, from left to right.
**
** Cells iMem through iMem+nCol are initialized to 0. The others are
** initialized to contain an SQL NULL.
*/
for (i = 0; i <= nCol; i++)
{
sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem + i);
}
for (i = 0; i < nCol; i++)
{
sqlite3VdbeAddOp2(v, OP_Null, 0, iMem + nCol + i + 1);
}
/* Start the analysis loop. This loop runs through all the entries in
** the index b-tree. */
endOfLoop = sqlite3VdbeMakeLabel(v);
sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
topOfLoop = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
for (i = 0; i < nCol; i++)
{
sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
CollSeq pColl;
if (i == 0)
{
#if SQLITE_ENABLE_STAT2
/* Check if the record that cursor iIdxCur points to contains a
** value that should be stored in the sqlite_stat2 table. If so,
** store it. */
int ne = sqlite3VdbeAddOp3( v, OP_Ne, regRecno, 0, regSamplerecno );
Debug.Assert( regTabname + 1 == regIdxname
&& regTabname + 2 == regSampleno
&& regTabname + 3 == regCol
);
sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL );
sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0 );
sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur + 1, regRowid );
sqlite3VdbeAddOp3( v, OP_Insert, iStatCur + 1, regRec, regRowid );
/* Calculate new values for regSamplerecno and regSampleno.
**
** sampleno = sampleno + 1
** samplerecno = samplerecno+(remaining records)/(remaining samples)
*/
sqlite3VdbeAddOp2( v, OP_AddImm, regSampleno, 1 );
sqlite3VdbeAddOp3( v, OP_Subtract, regRecno, regLast, regTemp );
sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 );
sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2 );
sqlite3VdbeAddOp3( v, OP_Subtract, regSampleno, regTemp2, regTemp2 );
sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regTemp, regTemp );
sqlite3VdbeAddOp3( v, OP_Add, regSamplerecno, regTemp, regSamplerecno );
sqlite3VdbeJumpHere( v, ne );
sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 );
#endif
/* Always record the very first row */
sqlite3VdbeAddOp1(v, OP_IfNot, iMem + 1);
}
Debug.Assert(pIdx.azColl != null);
Debug.Assert(pIdx.azColl[i] != null);
pColl = sqlite3LocateCollSeq(pParse, pIdx.azColl[i]);
sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem + nCol + i + 1,
pColl, P4_COLLSEQ);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
}
//if( db.mallocFailed ){
// /* If a malloc failure has occurred, then the result of the expression
// ** passed as the second argument to the call to sqlite3VdbeJumpHere()
// ** below may be negative. Which causes an Debug.Assert() to fail (or an
// ** out-of-bounds write if SQLITE_DEBUG is not defined). */
// return;
//}
sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
for (i = 0; i < nCol; i++)
{
int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol * 2);
if (i == 0)
{
sqlite3VdbeJumpHere(v, addr2 - 1); /* Set jump dest for the OP_IfNot */
}
sqlite3VdbeJumpHere(v, addr2); /* Set jump dest for the OP_Ne */
sqlite3VdbeAddOp2(v, OP_AddImm, iMem + i + 1, 1);
sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem + nCol + i + 1);
}
/* End of the analysis loop. */
sqlite3VdbeResolveLabel(v, endOfLoop);
sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
/* Store the results in sqlite_stat1.
**
** The result is a single row of the sqlite_stat1 table. The first
** two columns are the names of the table and index. The third column
** is a string composed of a list of integer statistics about the
** index. The first integer in the list is the total number of entries
** in the index. There is one additional integer in the list for each
** column of the table. This additional integer is a guess of how many
** rows of the table the index will select. If D is the count of distinct
** values and K is the total number of rows, then the integer is computed
** as:
**
** I = (K+D-1)/D
**
** If K==0 then no entry is made into the sqlite_stat1 table.
** If K>0 then it is always the case the D>0 so division by zero
** is never possible.
*/
sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
if (jZeroRows < 0)
{
jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
}
for (i = 0; i < nCol; i++)
{
sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem + i + 1, regTemp);
sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
sqlite3VdbeAddOp3(v, OP_Divide, iMem + i + 1, regTemp, regTemp);
sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
}
sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
}
/* If the table has no indices, create a single sqlite_stat1 entry
** containing NULL as the index name and the row count as the content.
*/
if (pTab.pIndex == null)
{
sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab.tnum, iDb);
VdbeComment(v, "%s", pTab.zName);
sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
}
else
{
sqlite3VdbeJumpHere(v, jZeroRows);
jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
}
sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
if (pParse.nMem < regRec)
pParse.nMem = regRec;
sqlite3VdbeJumpHere(v, jZeroRows);
}
/*
** Generate code that will cause the most recent index analysis to
** be loaded into internal hash tables where is can be used.
*/
static void loadAnalysis(Parse pParse, int iDb)
{
Vdbe v = sqlite3GetVdbe(pParse);
if (v != null)
{
sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
}
}
/*
** Generate code that will do an analysis of an entire database
*/
static void analyzeDatabase(Parse pParse, int iDb)
{
sqlite3 db = pParse.db;
Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */
HashElem k;
int iStatCur;
int iMem;
sqlite3BeginWriteOperation(pParse, 0, iDb);
iStatCur = pParse.nTab;
pParse.nTab += 2;
openStatTable(pParse, iDb, iStatCur, null, null);
iMem = pParse.nMem + 1;
Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
//for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){
for (k = pSchema.tblHash.first; k != null; k = k.next)
{
Table pTab = (Table)k.data;// sqliteHashData( k );
analyzeOneTable(pParse, pTab, null, iStatCur, iMem);
}
loadAnalysis(pParse, iDb);
}
/*
** Generate code that will do an analysis of a single table in
** a database. If pOnlyIdx is not NULL then it is a single index
** in pTab that should be analyzed.
*/
static void analyzeTable(Parse pParse, Table pTab, Index pOnlyIdx)
{
int iDb;
int iStatCur;
Debug.Assert(pTab != null);
Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
sqlite3BeginWriteOperation(pParse, 0, iDb);
iStatCur = pParse.nTab;
pParse.nTab += 2;
if (pOnlyIdx != null)
{
openStatTable(pParse, iDb, iStatCur, pOnlyIdx.zName, "idx");
}
else
{
openStatTable(pParse, iDb, iStatCur, pTab.zName, "tbl");
}
analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1);
loadAnalysis(pParse, iDb);
}
/*
** Generate code for the ANALYZE command. The parser calls this routine
** when it recognizes an ANALYZE command.
**
** ANALYZE -- 1
** ANALYZE <database> -- 2
** ANALYZE ?<database>.?<tablename> -- 3
**
** Form 1 causes all indices in all attached databases to be analyzed.
** Form 2 analyzes all indices the single database named.
** Form 3 analyzes all indices associated with the named table.
*/
// OVERLOADS, so I don't need to rewrite parse.c
static void sqlite3Analyze(Parse pParse, int null_2, int null_3)
{
sqlite3Analyze(pParse, null, null);
}
static void sqlite3Analyze(Parse pParse, Token pName1, Token pName2)
{
sqlite3 db = pParse.db;
int iDb;
int i;
string z, zDb;
Table pTab;
Index pIdx;
Token pTableName = null;
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
if (SQLITE_OK != sqlite3ReadSchema(pParse))
{
return;
}
Debug.Assert(pName2 != null || pName1 == null);
if (pName1 == null)
{
/* Form 1: Analyze everything */
for (i = 0; i < db.nDb; i++)
{
if (i == 1)
continue; /* Do not analyze the TEMP database */
analyzeDatabase(pParse, i);
}
}
else if (pName2.n == 0)
{
/* Form 2: Analyze the database or table named */
iDb = sqlite3FindDb(db, pName1);
if (iDb >= 0)
{
analyzeDatabase(pParse, iDb);
}
else
{
z = sqlite3NameFromToken(db, pName1);
if (z != null)
{
if ((pIdx = sqlite3FindIndex(db, z, null)) != null)
{
analyzeTable(pParse, pIdx.pTable, pIdx);
}
else if ((pTab = sqlite3LocateTable(pParse, 0, z, null)) != null)
{
analyzeTable(pParse, pTab, null);
}
z = null;//sqlite3DbFree( db, z );
}
}
}
else
{
/* Form 3: Analyze the fully qualified table name */
iDb = sqlite3TwoPartName(pParse, pName1, pName2, ref pTableName);
if (iDb >= 0)
{
zDb = db.aDb[iDb].zName;
z = sqlite3NameFromToken(db, pTableName);
if (z != null)
{
if ((pIdx = sqlite3FindIndex(db, z, zDb)) != null)
{
analyzeTable(pParse, pIdx.pTable, pIdx);
}
else if ((pTab = sqlite3LocateTable(pParse, 0, z, zDb)) != null)
{
analyzeTable(pParse, pTab, null);
}
z = null; //sqlite3DbFree( db, z );
}
}
}
}
/*
** Used to pass information from the analyzer reader through to the
** callback routine.
*/
//typedef struct analysisInfo analysisInfo;
public struct analysisInfo
{
public sqlite3 db;
public string zDatabase;
};
/*
** This callback is invoked once for each index when reading the
** sqlite_stat1 table.
**
** argv[0] = name of the table
** argv[1] = name of the index (might be NULL)
** argv[2] = results of analysis - on integer for each column
**
** Entries for which argv[1]==NULL simply record the number of rows in
** the table.
*/
static int analysisLoader(object pData, sqlite3_int64 argc, object Oargv, object NotUsed)
{
string[] argv = (string[])Oargv;
analysisInfo pInfo = (analysisInfo)pData;
Index pIndex;
Table pTable;
int i, c, n;
int v;
string z;
Debug.Assert(argc == 3);
UNUSED_PARAMETER2(NotUsed, argc);
if (argv == null || argv[0] == null || argv[2] == null)
{
return 0;
}
pTable = sqlite3FindTable(pInfo.db, argv[0], pInfo.zDatabase);
if (pTable == null)
{
return 0;
}
if (!String.IsNullOrEmpty(argv[1]))
{
pIndex = sqlite3FindIndex(pInfo.db, argv[1], pInfo.zDatabase);
}
else
{
pIndex = null;
}
n = pIndex != null ? pIndex.nColumn : 0;
z = argv[2];
int zIndex = 0;
for (i = 0; z != null && i <= n; i++)
{
v = 0;
while (zIndex < z.Length && (c = z[zIndex]) >= '0' && c <= '9')
{
v = v * 10 + c - '0';
zIndex++;
}
if (i == 0)
pTable.nRowEst = (uint)v;
if (pIndex == null)
break;
pIndex.aiRowEst[i] = v;
if (zIndex < z.Length && z[zIndex] == ' ')
zIndex++;
if (z.Substring(zIndex).CompareTo("unordered") == 0)//memcmp( z, "unordered", 10 ) == 0 )
{
pIndex.bUnordered = 1;
break;
}
}
return 0;
}
/*
** If the Index.aSample variable is not NULL, delete the aSample[] array
** and its contents.
*/
static void sqlite3DeleteIndexSamples(sqlite3 db, Index pIdx)
{
#if SQLITE_ENABLE_STAT2
if ( pIdx.aSample != null )
{
int j;
for ( j = 0; j < SQLITE_INDEX_SAMPLES; j++ )
{
IndexSample p = pIdx.aSample[j];
if ( p.eType == SQLITE_TEXT || p.eType == SQLITE_BLOB )
{
p.u.z = null;//sqlite3DbFree(db, p.u.z);
p.u.zBLOB = null;
}
}
sqlite3DbFree( db, ref pIdx.aSample );
}
#else
UNUSED_PARAMETER(db);
UNUSED_PARAMETER(pIdx);
#endif
}
/*
** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
** arrays. The contents of sqlite_stat2 are used to populate the
** Index.aSample[] arrays.
**
** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
** during compilation and the sqlite_stat2 table is present, no data is
** read from it.
**
** If SQLITE_ENABLE_STAT2 was defined during compilation and the
** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
** returned. However, in this case, data is read from the sqlite_stat1
** table (if it is present) before returning.
**
** If an OOM error occurs, this function always sets db.mallocFailed.
** This means if the caller does not care about other errors, the return
** code may be ignored.
*/
static int sqlite3AnalysisLoad(sqlite3 db, int iDb)
{
analysisInfo sInfo;
HashElem i;
string zSql;
int rc;
Debug.Assert(iDb >= 0 && iDb < db.nDb);
Debug.Assert(db.aDb[iDb].pBt != null);
/* Clear any prior statistics */
Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
//for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){
for (i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next)
{
Index pIdx = (Index)i.data;// sqliteHashData( i );
sqlite3DefaultRowEst(pIdx);
sqlite3DeleteIndexSamples(db, pIdx);
pIdx.aSample = null;
}
/* Check to make sure the sqlite_stat1 table exists */
sInfo.db = db;
sInfo.zDatabase = db.aDb[iDb].zName;
if (sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase) == null)
{
return SQLITE_ERROR;
}
/* Load new statistics out of the sqlite_stat1 table */
zSql = sqlite3MPrintf(db,
"SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
//if ( zSql == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
{
rc = sqlite3_exec(db, zSql, (dxCallback)analysisLoader, sInfo, 0);
sqlite3DbFree(db, ref zSql);
}
/* Load the statistics from the sqlite_stat2 table. */
#if SQLITE_ENABLE_STAT2
if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) )
{
rc = SQLITE_ERROR;
}
if ( rc == SQLITE_OK )
{
sqlite3_stmt pStmt = null;
zSql = sqlite3MPrintf( db,
"SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase );
//if( null==zSql ){
//rc = SQLITE_NOMEM;
//}else{
rc = sqlite3_prepare( db, zSql, -1, ref pStmt, 0 );
sqlite3DbFree( db, ref zSql );
//}
if ( rc == SQLITE_OK )
{
while ( sqlite3_step( pStmt ) == SQLITE_ROW )
{
string zIndex; /* Index name */
Index pIdx; /* Pointer to the index object */
zIndex = sqlite3_column_text( pStmt, 0 );
pIdx = !String.IsNullOrEmpty( zIndex ) ? sqlite3FindIndex( db, zIndex, sInfo.zDatabase ) : null;
if ( pIdx != null )
{
int iSample = sqlite3_column_int( pStmt, 1 );
if ( iSample < SQLITE_INDEX_SAMPLES && iSample >= 0 )
{
int eType = sqlite3_column_type( pStmt, 2 );
if ( pIdx.aSample == null )
{
//static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
//pIdx->aSample = (IndexSample )sqlite3DbMallocRaw(0, sz);
//if( pIdx.aSample==0 ){
//db.mallocFailed = 1;
//break;
//}
pIdx.aSample = new IndexSample[SQLITE_INDEX_SAMPLES];//memset(pIdx->aSample, 0, sz);
}
//Debug.Assert( pIdx.aSample != null );
if ( pIdx.aSample[iSample] == null )
pIdx.aSample[iSample] = new IndexSample();
IndexSample pSample = pIdx.aSample[iSample];
{
pSample.eType = (u8)eType;
if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT )
{
pSample.u.r = sqlite3_column_double( pStmt, 2 );
}
else if ( eType == SQLITE_TEXT || eType == SQLITE_BLOB )
{
string z = null;
byte[] zBLOB = null;
//string z = (string )(
//(eType==SQLITE_BLOB) ?
//sqlite3_column_blob(pStmt, 2):
//sqlite3_column_text(pStmt, 2)
//);
if ( eType == SQLITE_BLOB )
zBLOB = sqlite3_column_blob( pStmt, 2 );
else
z = sqlite3_column_text( pStmt, 2 );
int n = sqlite3_column_bytes( pStmt, 2 );
if ( n > 24 )
{
n = 24;
}
pSample.nByte = (u8)n;
if ( n < 1 )
{
pSample.u.z = null;
pSample.u.zBLOB = null;
}
else
{
pSample.u.z = z;
pSample.u.zBLOB = zBLOB;
//pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
//if( pSample->u.z ){
// memcpy(pSample->u.z, z, n);
//}else{
// db->mallocFailed = 1;
// break;
//}
}
}
}
}
}
}
rc = sqlite3_finalize( pStmt );
}
}
#endif
//if( rc==SQLITE_NOMEM ){
// db.mallocFailed = 1;
//}
return rc;
}
#endif // * SQLITE_OMIT_ANALYZE */
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComProcurement.Purchase.DS
{
public class PO_AdditionChargesDS
{
public PO_AdditionChargesDS()
{
}
private const string THIS = "PCSComProcurement.Purchase.DS.DS.PO_AdditionChargesDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to PO_AdditionCharges
/// </Description>
/// <Inputs>
/// PO_AdditionChargesVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, March 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
PO_AdditionChargesVO objObject = (PO_AdditionChargesVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO PO_AdditionCharges("
+ PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + ","
+ PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ PO_AdditionChargesTable.REASONID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.AMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.AMOUNT_FLD].Value = objObject.Amount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.VATAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.VATAMOUNT_FLD].Value = objObject.VatAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.TOTALAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.TOTALAMOUNT_FLD].Value = objObject.TotalAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD].Value = objObject.PurchaseOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD].Value = objObject.PurchaseOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.ADDCHARGEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.ADDCHARGEID_FLD].Value = objObject.AddChargeID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.REASONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.REASONID_FLD].Value = objObject.ReasonID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from PO_AdditionCharges
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql = "DELETE " + PO_AdditionChargesTable.TABLE_NAME + " WHERE " + "AdditionChargesID" + "=" + pintID.ToString();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from PO_AdditionCharges
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// PO_AdditionChargesVO
/// </Outputs>
/// <Returns>
/// PO_AdditionChargesVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, March 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + ","
+ PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + ","
+ PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ PO_AdditionChargesTable.REASONID_FLD
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME
+ " WHERE " + PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
PO_AdditionChargesVO objObject = new PO_AdditionChargesVO();
while (odrPCS.Read())
{
objObject.AdditionChargesID = int.Parse(odrPCS[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD].ToString());
objObject.Quantity = Decimal.Parse(odrPCS[PO_AdditionChargesTable.QUANTITY_FLD].ToString());
objObject.UnitPrice = Decimal.Parse(odrPCS[PO_AdditionChargesTable.UNITPRICE_FLD].ToString());
objObject.Amount = Decimal.Parse(odrPCS[PO_AdditionChargesTable.AMOUNT_FLD].ToString());
objObject.VatAmount = Decimal.Parse(odrPCS[PO_AdditionChargesTable.VATAMOUNT_FLD].ToString());
objObject.TotalAmount = Decimal.Parse(odrPCS[PO_AdditionChargesTable.TOTALAMOUNT_FLD].ToString());
objObject.PurchaseOrderDetailID = int.Parse(odrPCS[PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD].ToString());
objObject.PurchaseOrderMasterID = int.Parse(odrPCS[PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD].ToString());
objObject.AddChargeID = int.Parse(odrPCS[PO_AdditionChargesTable.ADDCHARGEID_FLD].ToString());
objObject.ReasonID = int.Parse(odrPCS[PO_AdditionChargesTable.REASONID_FLD].ToString());
}
return objObject;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to PO_AdditionCharges
/// </Description>
/// <Inputs>
/// PO_AdditionChargesVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
PO_AdditionChargesVO objObject = (PO_AdditionChargesVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql = "UPDATE PO_AdditionCharges SET "
+ PO_AdditionChargesTable.QUANTITY_FLD + "= ?" + ","
+ PO_AdditionChargesTable.UNITPRICE_FLD + "= ?" + ","
+ PO_AdditionChargesTable.AMOUNT_FLD + "= ?" + ","
+ PO_AdditionChargesTable.VATAMOUNT_FLD + "= ?" + ","
+ PO_AdditionChargesTable.TOTALAMOUNT_FLD + "= ?" + ","
+ PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + "= ?" + ","
+ PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + "= ?" + ","
+ PO_AdditionChargesTable.ADDCHARGEID_FLD + "= ?" + ","
+ PO_AdditionChargesTable.REASONID_FLD + "= ?"
+ " WHERE " + PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.AMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.AMOUNT_FLD].Value = objObject.Amount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.VATAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.VATAMOUNT_FLD].Value = objObject.VatAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.TOTALAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PO_AdditionChargesTable.TOTALAMOUNT_FLD].Value = objObject.TotalAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD].Value = objObject.PurchaseOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD].Value = objObject.PurchaseOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.ADDCHARGEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.ADDCHARGEID_FLD].Value = objObject.AddChargeID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.REASONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.REASONID_FLD].Value = objObject.ReasonID;
ocmdPCS.Parameters.Add(new OleDbParameter(PO_AdditionChargesTable.ADDITIONCHARGESID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD].Value = objObject.AdditionChargesID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PO_AdditionCharges
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, March 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + ","
+ PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + ","
+ PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ PO_AdditionChargesTable.REASONID_FLD
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, PO_AdditionChargesTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PO_AdditionCharges
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, March 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT 0 AS 'ChargeLine', "
+ PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + ","
+ PO_PurchaseOrderDetailTable.LINE_FLD + " AS " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD + ","
+ MST_AddChargeTable.TABLE_NAME + "." + MST_AddChargeTable.CODE_FLD + " AS " + MST_AddChargeTable.TABLE_NAME + MST_AddChargeTable.CODE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ MST_ReasonTable.TABLE_NAME + "." + MST_ReasonTable.CODE_FLD + " AS " + MST_ReasonTable.TABLE_NAME + MST_ReasonTable.CODE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.REASONID_FLD + ","
+ PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ pintPOMasterID + " AS " + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME
+ " JOIN " + PO_PurchaseOrderDetailTable.TABLE_NAME
+ " ON " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD
+ " = " + PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD
+ " JOIN " + MST_AddChargeTable.TABLE_NAME
+ " ON " + MST_AddChargeTable.TABLE_NAME + "." + MST_AddChargeTable.ADDCHARGEID_FLD
+ " = " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.ADDCHARGEID_FLD
+ " JOIN " + MST_ReasonTable.TABLE_NAME
+ " ON " + MST_ReasonTable.TABLE_NAME + "." + MST_ReasonTable.REASONID_FLD
+ " = " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.REASONID_FLD
+ " WHERE " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
//+ " AND " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, PO_AdditionChargesTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, March 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + ","
+ PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + ","
+ PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ PO_AdditionChargesTable.REASONID_FLD
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, PO_AdditionChargesTable.TABLE_NAME);
}
catch (OleDbException ex)
{
if (ex.Errors.Count > 0)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to check UM of all products
/// </Description>
/// <Inputs>
/// int POMaterID
/// </Inputs>
/// <Outputs>
/// return true if all of product have same UM
/// else return false
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 07-Mar-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public bool IsChargeByQuantity(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".IsChargeByQuantity()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT DISTINCT "
+ PO_PurchaseOrderDetailTable.BUYINGUMID_FLD
+ " FROM " + PO_PurchaseOrderDetailTable.TABLE_NAME
+ " WHERE " + PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, SO_SaleOrderDetailTable.TABLE_NAME);
// if data set return more than one row then return false
if (dstPCS.Tables[SO_SaleOrderDetailTable.TABLE_NAME].Rows.Count > 1)
{
return false;
}
else
{
return true;
}
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get additional charge by PO Master
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 17-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetAdditionalChargeByPOMasterID(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".GetAdditionalChargeByPOMasterID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.LINE_FLD + " AS " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD + ","
+ MST_AddChargeTable.TABLE_NAME + "." + MST_AddChargeTable.CODE_FLD + " AS " + MST_AddChargeTable.TABLE_NAME + MST_AddChargeTable.CODE_FLD + ","
//+ MST_ReasonTable.TABLE_NAME + "." + MST_ReasonTable.CODE_FLD + " AS " + MST_ReasonTable.TABLE_NAME + MST_ReasonTable.CODE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.AMOUNT_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.VATAMOUNT_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.TOTALAMOUNT_FLD + ","
+ PO_AdditionChargesTable.ADDITIONCHARGESID_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.ADDCHARGEID_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.REASONID_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD + " as " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.UNITPRICE_FLD + " as " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME
+ " JOIN " + PO_PurchaseOrderDetailTable.TABLE_NAME
+ " ON " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD
+ " = " + PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD
+ " JOIN " + MST_AddChargeTable.TABLE_NAME
+ " ON " + MST_AddChargeTable.TABLE_NAME + "." + MST_AddChargeTable.ADDCHARGEID_FLD
+ " = " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.ADDCHARGEID_FLD
// + " JOIN " + MST_ReasonTable.TABLE_NAME
// + " ON " + MST_ReasonTable.TABLE_NAME + "." + MST_ReasonTable.REASONID_FLD
// + " = " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.REASONID_FLD
+ " WHERE " + PO_AdditionChargesTable.TABLE_NAME + "." + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
// create table to hold data
DataTable tblData = new DataTable(PO_AdditionChargesTable.TABLE_NAME);
DataColumn dcolLine = new DataColumn("Line", typeof (int));
dcolLine.AutoIncrement = true;
dcolLine.AutoIncrementSeed = 1;
dcolLine.AutoIncrementStep = 1;
tblData.Columns.Add(dcolLine);
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(MST_AddChargeTable.TABLE_NAME + MST_AddChargeTable.CODE_FLD, typeof(string)));
tblData.Columns.Add(new DataColumn(MST_ReasonTable.TABLE_NAME + MST_ReasonTable.CODE_FLD, typeof(string)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.QUANTITY_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.UNITPRICE_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.AMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.VATAMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.TOTALAMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.ADDITIONCHARGESID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.ADDCHARGEID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.REASONID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_AdditionChargesTable.QUANTITY_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_AdditionChargesTable.UNITPRICE_FLD, typeof(decimal)));
// primary key
// DataColumn[] dcolKey = new DataColumn[1];
// dcolKey[0] = tblData.Columns[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD];
// tblData.PrimaryKey = dcolKey;
// fill data
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(tblData);
// add table to dataset
dstPCS.Tables.Add(tblData);
// return
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from PO detail by PO Master
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 17-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetDataByPOMasterID(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".GetDataByPOMasterID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.LINE_FLD + " AS " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD + ","
+ " 0 AS " + PO_AdditionChargesTable.QUANTITY_FLD + ","
+ "0 AS " + PO_PurchaseOrderDetailTable.UNITPRICE_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD + " AS " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.QUANTITY_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.UNITPRICE_FLD + " AS " + PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.UNITPRICE_FLD + ","
+ PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD
+ " FROM " + PO_PurchaseOrderDetailTable.TABLE_NAME
+ " WHERE " + PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
//+ " AND " + PO_PurchaseOrderDetailTable.APPROVERID_FLD + " > 0";
// create table to hold data
DataTable tblData = new DataTable(PO_AdditionChargesTable.TABLE_NAME);
DataColumn dcolLine = new DataColumn("Line", typeof (int));
dcolLine.AutoIncrement = true;
dcolLine.AutoIncrementSeed = 1;
dcolLine.AutoIncrementStep = 1;
tblData.Columns.Add(dcolLine);
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(MST_AddChargeTable.TABLE_NAME + MST_AddChargeTable.CODE_FLD, typeof(string)));
tblData.Columns.Add(new DataColumn(MST_ReasonTable.TABLE_NAME + MST_ReasonTable.CODE_FLD, typeof(string)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.QUANTITY_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.UNITPRICE_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.AMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.VATAMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.TOTALAMOUNT_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.ADDITIONCHARGESID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.ADDCHARGEID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.REASONID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.PURCHASEORDERDETAILID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD, typeof(int)));
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.UNITPRICE_FLD, typeof(decimal)));
tblData.Columns.Add(new DataColumn(PO_PurchaseOrderDetailTable.TABLE_NAME + PO_AdditionChargesTable.QUANTITY_FLD, typeof(decimal)));
tblData.Columns[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD].AutoIncrement = true;
tblData.Columns[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD].AutoIncrementSeed = 1;
tblData.Columns[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD].AutoIncrementStep = 1;
// primary key
// DataColumn[] dcolKey = new DataColumn[1];
// dcolKey[0] = tblData.Columns[PO_AdditionChargesTable.ADDITIONCHARGESID_FLD];
// tblData.PrimaryKey = dcolKey;
// fill data
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable tblTemp = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(tblTemp);
foreach (DataRow drowData in tblTemp.Rows)
{
DataRow drowNew = tblData.NewRow();
foreach (DataColumn dcolData in tblTemp.Columns)
{
drowNew[dcolData.ColumnName] = drowData[dcolData.ColumnName];
}
tblData.Rows.Add(drowNew);
}
// add table to dataset
dstPCS.Tables.Add(tblData);
// return
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data for SOLine dropdown
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// DataTable
/// </Outputs>
/// <Returns>
/// DataTable
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 17-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetPODetailByPOMaster(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".GetPODetailByPOMaster()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT " + PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD
+ " FROM " + PO_PurchaseOrderDetailTable.TABLE_NAME
+ " WHERE " + PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, PO_PurchaseOrderDetailTable.TABLE_NAME);
return dstPCS.Tables[PO_PurchaseOrderDetailTable.TABLE_NAME];
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to check a PO Master was charged or not
/// </Description>
/// <Inputs>
/// Purchase Order Master ID (int)
/// </Inputs>
/// <Outputs>
/// return true if charged
/// else return false
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 18-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public bool AlreadyCharged(int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".AlreadyCharged()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT ISNULL(COUNT(*), 0) "
+ " FROM " + PO_AdditionChargesTable.TABLE_NAME
+ " WHERE " + PO_AdditionChargesTable.PURCHASEORDERMASTERID_FLD + "=" + pintPOMasterID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult != null)
{
if (int.Parse(objResult.ToString()) > 0)
return true;
else
return false;
}
else
return false;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//
// ServiceController.cs
//
// Author:
// Scott Thomas <[email protected]>
//
// Copyright (C) 2008 S&S Black Ltd.
//
// 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 Mono.Upnp.Internal;
using Mono.Upnp.Xml;
namespace Mono.Upnp.Control
{
[XmlType ("scpd", Protocol.ServiceSchema)]
public class ServiceController :
Description,
IXmlDeserializable,
IXmlDeserializer<ServiceAction>,
IXmlDeserializer<StateVariable>
{
DataServer scpd_server;
ControlServer control_server;
ControlClient control_client;
EventServer event_server;
EventClient event_client;
CollectionMap<string, ServiceAction> actions;
CollectionMap<string, StateVariable> state_variables;
protected internal ServiceController (Deserializer deserializer, Service service)
: base (deserializer)
{
if (service == null) {
throw new ArgumentNullException ("service");
} else if (service.ControlUrl == null) {
throw new ArgumentException ("The service has no ControlUrl.", "service");
} else if (service.EventUrl == null) {
throw new ArgumentException ("The service has no EventUrl.", "service");
}
actions = new CollectionMap<string, ServiceAction> ();
state_variables = new CollectionMap<string, StateVariable> ();
control_client = new ControlClient (
service.Type.ToString (), service.ControlUrl, deserializer.XmlDeserializer);
event_client = new EventClient (state_variables, service.EventUrl);
}
public ServiceController (IEnumerable<ServiceAction> actions, IEnumerable<StateVariable> stateVariables)
{
this.actions = Helper.MakeReadOnlyCopy<string, ServiceAction> (actions);
this.state_variables = Helper.MakeReadOnlyCopy<string, StateVariable> (stateVariables);
SpecVersion = new SpecVersion (1, 1);
}
[XmlAttribute ("configId")]
protected internal virtual string ConfigurationId { get; set; }
[XmlElement ("specVersion")]
public virtual SpecVersion SpecVersion { get; protected set; }
[XmlArray ("actionList")]
protected virtual ICollection<ServiceAction> ActionCollection {
get { return actions; }
}
public IMap<string, ServiceAction> Actions {
get { return actions; }
}
[XmlArray ("serviceStateTable")]
protected virtual ICollection<StateVariable> StateVariableCollection {
get { return state_variables; }
}
public IMap<string, StateVariable> StateVariables {
get { return state_variables; }
}
protected internal virtual void Initialize (XmlSerializer serializer, Service service)
{
if (serializer == null) {
throw new ArgumentNullException ("serializer");
} else if (service == null) {
throw new ArgumentNullException ("service");
} else if (service.ScpdUrl == null) {
throw new ArgumentException ("The service has no ScpdUrl.", "service");
} else if (service.ControlUrl == null) {
throw new ArgumentException ("The service has no ControlUrl.", "service");
} else if (service.EventUrl == null) {
throw new ArgumentException ("The service has no EventUrl.", "service");
}
scpd_server = new DataServer (serializer.GetBytes (this), @"text/xml; charset=""utf-8""", service.ScpdUrl);
control_server = new ControlServer (actions, service.Type.ToString (), service.ControlUrl, serializer);
event_server = new EventServer (state_variables.Values, service.EventUrl);
foreach (var state_variable in state_variables.Values) {
state_variable.Initialize (this);
}
}
protected internal virtual void Start ()
{
if (scpd_server == null) {
throw new InvalidOperationException ("The service controller has not been initialized.");
}
scpd_server.Start ();
control_server.Start ();
event_server.Start ();
}
protected internal virtual void Stop ()
{
if (scpd_server == null) {
throw new InvalidOperationException ("The service controller has not been initialized.");
}
scpd_server.Stop ();
control_server.Stop ();
event_server.Stop ();
}
protected internal virtual IMap<string, string> Invoke (ServiceAction action,
IDictionary<string, string> arguments,
int retryAttempts)
{
// TODO try dispose on timeout
// TODO retry attempts
if (control_client == null) {
throw new InvalidOperationException (
"The service controller was created to describe a local service and cannot be invoked " +
"across the network. Use the constructor which takes a Deserializer.");
}
return control_client.Invoke (action.Name, arguments);
}
internal void RefEvents ()
{
event_client.Ref ();
}
internal void UnrefEvents ()
{
event_client.Unref ();
}
internal void UpdateStateVariable (StateVariable stateVariable)
{
event_server.QueueUpdate (stateVariable);
}
ServiceAction IXmlDeserializer<ServiceAction>.Deserialize (XmlDeserializationContext context)
{
return DeserializeAction (context);
}
protected virtual ServiceAction DeserializeAction (XmlDeserializationContext context)
{
return Deserializer != null ? Deserializer.DeserializeAction (this, context) : null;
}
StateVariable IXmlDeserializer<StateVariable>.Deserialize (XmlDeserializationContext context)
{
return DeserializeStateVariable (context);
}
protected virtual StateVariable DeserializeStateVariable (XmlDeserializationContext context)
{
return Deserializer != null ? Deserializer.DeserializeStateVariable (this, context) : null;
}
void IXmlDeserializable.Deserialize (XmlDeserializationContext context)
{
Deserialize (context);
actions.MakeReadOnly ();
state_variables.MakeReadOnly ();
}
void IXmlDeserializable.DeserializeAttribute (XmlDeserializationContext context)
{
DeserializeAttribute (context);
}
void IXmlDeserializable.DeserializeElement (XmlDeserializationContext context)
{
DeserializeElement (context);
}
protected override void DeserializeElement (XmlDeserializationContext context)
{
AutoDeserializeElement (this, context);
}
protected override void Serialize (Mono.Upnp.Xml.XmlSerializationContext context)
{
AutoSerialize (this, context);
}
protected override void SerializeMembers (XmlSerializationContext context)
{
AutoSerializeMembers (this, context);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowGroupedWithinSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using Akka.Util.Internal.Collections;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using static Akka.Streams.Tests.Dsl.TestConfig;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowGroupedWithinSpec : ScriptedTest
{
private ActorMaterializerSettings Settings { get; }
private ActorMaterializer Materializer { get; }
public FlowGroupedWithinSpec(ITestOutputHelper helper) : base(helper)
{
Settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, Settings);
}
[Fact]
public void A_GroupedWithin_must_group_elements_within_the_duration()
{
this.AssertAllStagesStopped(() =>
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromSeconds(1))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(100);
var demand1 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand1; i++)
pSub.SendNext(input.Next());
var demand2 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand2; i++)
pSub.SendNext(input.Next());
var demand3 = (int)pSub.ExpectRequest();
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(1, demand1 + demand2));
for (var i = 1; i <= demand3; i++)
pSub.SendNext(input.Next());
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
c.ExpectNext()
.ShouldAllBeEquivalentTo(Enumerable.Range(demand1 + demand2 + 1, demand3));
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
pSub.ExpectRequest();
var last = input.Next();
pSub.SendNext(last);
pSub.SendComplete();
c.ExpectNext().Should().HaveCount(1).And.HaveElementAt(0, last);
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}, Materializer);
}
[Fact]
public void A_GroupedWithin_must_deliver_buffered_elements_OnComplete_before_the_timeout()
{
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.From(Enumerable.Range(1, 3))
.GroupedWithin(1000, TimeSpan.FromSeconds(10))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var cSub = c.ExpectSubscription();
cSub.Request(100);
c.ExpectNext().ShouldAllBeEquivalentTo(new[] { 1, 2, 3 });
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}
[Fact]
public void A_GroupedWithin_must_buffer_groups_until_requested_from_downstream()
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromSeconds(1))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(1);
var demand1 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand1; i++)
pSub.SendNext(input.Next());
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(1, demand1));
var demand2 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand2; i++)
pSub.SendNext(input.Next());
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
cSub.Request(1);
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(demand1 + 1, demand2));
pSub.SendComplete();
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_drop_empty_groups()
{
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromMilliseconds(500))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(2);
pSub.ExpectRequest();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(600));
pSub.SendNext(1);
pSub.SendNext(2);
c.ExpectNext().ShouldAllBeEquivalentTo(new [] {1,2});
// nothing more requested
c.ExpectNoMsg(TimeSpan.FromMilliseconds(1100));
cSub.Request(3);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(600));
pSub.SendComplete();
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_reset_time_window_when_max_elements_reached()
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(upstream)
.GroupedWithin(3, TimeSpan.FromSeconds(2))
.To(Sink.FromSubscriber(downstream))
.Run(Materializer);
downstream.Request(2);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1000));
Enumerable.Range(1,4).ForEach(_=>upstream.SendNext(input.Next()));
downstream.Within(TimeSpan.FromMilliseconds(1000), () =>
{
downstream.ExpectNext().ShouldAllBeEquivalentTo(new[] {1, 2, 3});
return NotUsed.Instance;
});
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1500));
downstream.Within(TimeSpan.FromMilliseconds(1000), () =>
{
downstream.ExpectNext().ShouldAllBeEquivalentTo(new[] {4});
return NotUsed.Instance;
});
upstream.SendComplete();
downstream.ExpectComplete();
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_group_early()
{
var random = new Random();
var script = Script.Create(RandomTestRange(Sys).Select(_ =>
{
var x = random.Next();
var y = random.Next();
var z = random.Next();
return Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] {x, y, z},
new[] {new[] {x, y, z}});
}).ToArray());
RandomTestRange(Sys)
.ForEach(_ => RunScript(script, Settings, flow => flow.GroupedWithin(3, TimeSpan.FromMinutes(10))));
}
[Fact]
public void A_GroupedWithin_must_group_with_rest()
{
var random = new Random();
Func<Script<int, IEnumerable<int>>> script = () =>
{
var i = random.Next();
var rest = Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] {i}, new[] {new[] {i}});
return Script.Create(RandomTestRange(Sys).Select(_ =>
{
var x = random.Next();
var y = random.Next();
var z = random.Next();
return Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] { x, y, z },
new[] { new[] { x, y, z }});
}).Concat(rest).ToArray());
};
RandomTestRange(Sys)
.ForEach(_ => RunScript(script(), Settings, flow => flow.GroupedWithin(3, TimeSpan.FromMinutes(10))));
}
[Fact]
public void A_GroupedWithin_must_group_with_small_groups_with_backpressure()
{
var t = Source.From(Enumerable.Range(1, 10))
.GroupedWithin(1, TimeSpan.FromDays(1))
.Throttle(1, TimeSpan.FromMilliseconds(110), 0, ThrottleMode.Shaping)
.RunWith(Sink.Seq<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10).Select(i => new List<int> {i}));
}
}
}
| |
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Search.Spans
{
using Lucene.Net.Index;
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexReaderContext = Lucene.Net.Index.IndexReaderContext;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using ReaderUtil = Lucene.Net.Index.ReaderUtil;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Term = Lucene.Net.Index.Term;
[TestFixture]
public class TestSpans : LuceneTestCase
{
private IndexSearcher Searcher;
private IndexReader Reader;
private Directory Directory;
public const string field = "field";
[SetUp]
public override void SetUp()
{
base.SetUp();
Directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
for (int i = 0; i < DocFields.Length; i++)
{
Document doc = new Document();
doc.Add(NewTextField(field, DocFields[i], Field.Store.YES));
writer.AddDocument(doc);
}
Reader = writer.Reader;
writer.Dispose();
Searcher = NewSearcher(Reader);
}
[TearDown]
public override void TearDown()
{
Reader.Dispose();
Directory.Dispose();
base.TearDown();
}
private string[] DocFields = new string[] { "w1 w2 w3 w4 w5", "w1 w3 w2 w3", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3", "u2 u2 u1", "u2 xx u2 u1", "u2 u2 xx u1", "u2 xx u2 yy u1", "u2 xx u1 u2", "u2 u1 xx u2", "u1 u2 xx u2", "t1 t2 t1 t3 t2 t3", "s2 s1 s1 xx xx s2 xx s2 xx s1 xx xx xx xx xx s2 xx" };
public virtual SpanTermQuery MakeSpanTermQuery(string text)
{
return new SpanTermQuery(new Term(field, text));
}
private void CheckHits(Query query, int[] results)
{
Search.CheckHits.DoCheckHits(Random(), query, field, Searcher, results);
}
private void OrderedSlopTest3SQ(SpanQuery q1, SpanQuery q2, SpanQuery q3, int slop, int[] expectedDocs)
{
bool ordered = true;
SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { q1, q2, q3 }, slop, ordered);
CheckHits(snq, expectedDocs);
}
public virtual void OrderedSlopTest3(int slop, int[] expectedDocs)
{
OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w2"), MakeSpanTermQuery("w3"), slop, expectedDocs);
}
public virtual void OrderedSlopTest3Equal(int slop, int[] expectedDocs)
{
OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w3"), MakeSpanTermQuery("w3"), slop, expectedDocs);
}
public virtual void OrderedSlopTest1Equal(int slop, int[] expectedDocs)
{
OrderedSlopTest3SQ(MakeSpanTermQuery("u2"), MakeSpanTermQuery("u2"), MakeSpanTermQuery("u1"), slop, expectedDocs);
}
[Test]
public virtual void TestSpanNearOrdered01()
{
OrderedSlopTest3(0, new int[] { 0 });
}
[Test]
public virtual void TestSpanNearOrdered02()
{
OrderedSlopTest3(1, new int[] { 0, 1 });
}
[Test]
public virtual void TestSpanNearOrdered03()
{
OrderedSlopTest3(2, new int[] { 0, 1, 2 });
}
[Test]
public virtual void TestSpanNearOrdered04()
{
OrderedSlopTest3(3, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSpanNearOrdered05()
{
OrderedSlopTest3(4, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSpanNearOrderedEqual01()
{
OrderedSlopTest3Equal(0, new int[] { });
}
[Test]
public virtual void TestSpanNearOrderedEqual02()
{
OrderedSlopTest3Equal(1, new int[] { 1 });
}
[Test]
public virtual void TestSpanNearOrderedEqual03()
{
OrderedSlopTest3Equal(2, new int[] { 1 });
}
[Test]
public virtual void TestSpanNearOrderedEqual04()
{
OrderedSlopTest3Equal(3, new int[] { 1, 3 });
}
[Test]
public virtual void TestSpanNearOrderedEqual11()
{
OrderedSlopTest1Equal(0, new int[] { 4 });
}
[Test]
public virtual void TestSpanNearOrderedEqual12()
{
OrderedSlopTest1Equal(0, new int[] { 4 });
}
[Test]
public virtual void TestSpanNearOrderedEqual13()
{
OrderedSlopTest1Equal(1, new int[] { 4, 5, 6 });
}
[Test]
public virtual void TestSpanNearOrderedEqual14()
{
OrderedSlopTest1Equal(2, new int[] { 4, 5, 6, 7 });
}
[Test]
public virtual void TestSpanNearOrderedEqual15()
{
OrderedSlopTest1Equal(3, new int[] { 4, 5, 6, 7 });
}
[Test]
public virtual void TestSpanNearOrderedOverlap()
{
bool ordered = true;
int slop = 1;
SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2"), MakeSpanTermQuery("t3") }, slop, ordered);
Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq);
Assert.IsTrue(spans.Next(), "first range");
Assert.AreEqual(11, spans.Doc(), "first doc");
Assert.AreEqual(0, spans.Start(), "first start");
Assert.AreEqual(4, spans.End(), "first end");
Assert.IsTrue(spans.Next(), "second range");
Assert.AreEqual(11, spans.Doc(), "second doc");
Assert.AreEqual(2, spans.Start(), "second start");
Assert.AreEqual(6, spans.End(), "second end");
Assert.IsFalse(spans.Next(), "third range");
}
[Test]
public virtual void TestSpanNearUnOrdered()
{
//See http://www.gossamer-threads.com/lists/lucene/java-dev/52270 for discussion about this test
SpanNearQuery snq;
snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2") }, 0, false);
Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq);
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(4, spans.Doc(), "doc");
Assert.AreEqual(1, spans.Start(), "start");
Assert.AreEqual(3, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(5, spans.Doc(), "doc");
Assert.AreEqual(2, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(8, spans.Doc(), "doc");
Assert.AreEqual(2, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(9, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(2, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(10, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(2, spans.End(), "end");
Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't: " + spans.Doc());
SpanNearQuery u1u2 = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2") }, 0, false);
snq = new SpanNearQuery(new SpanQuery[] { u1u2, MakeSpanTermQuery("u2") }, 1, false);
spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq);
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(4, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(3, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
//unordered spans can be subsets
Assert.AreEqual(4, spans.Doc(), "doc");
Assert.AreEqual(1, spans.Start(), "start");
Assert.AreEqual(3, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(5, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(5, spans.Doc(), "doc");
Assert.AreEqual(2, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(8, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(8, spans.Doc(), "doc");
Assert.AreEqual(2, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(9, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(2, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(9, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(4, spans.End(), "end");
Assert.IsTrue(spans.Next(), "Does not have next and it should");
Assert.AreEqual(10, spans.Doc(), "doc");
Assert.AreEqual(0, spans.Start(), "start");
Assert.AreEqual(2, spans.End(), "end");
Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't");
}
private Spans OrSpans(string[] terms)
{
SpanQuery[] sqa = new SpanQuery[terms.Length];
for (int i = 0; i < terms.Length; i++)
{
sqa[i] = MakeSpanTermQuery(terms[i]);
}
return MultiSpansWrapper.Wrap(Searcher.TopReaderContext, new SpanOrQuery(sqa));
}
private void TstNextSpans(Spans spans, int doc, int start, int end)
{
Assert.IsTrue(spans.Next(), "next");
Assert.AreEqual(doc, spans.Doc(), "doc");
Assert.AreEqual(start, spans.Start(), "start");
Assert.AreEqual(end, spans.End(), "end");
}
[Test]
public virtual void TestSpanOrEmpty()
{
Spans spans = OrSpans(new string[0]);
Assert.IsFalse(spans.Next(), "empty next");
SpanOrQuery a = new SpanOrQuery();
SpanOrQuery b = new SpanOrQuery();
Assert.IsTrue(a.Equals(b), "empty should equal");
}
[Test]
public virtual void TestSpanOrSingle()
{
Spans spans = OrSpans(new string[] { "w5" });
TstNextSpans(spans, 0, 4, 5);
Assert.IsFalse(spans.Next(), "final next");
}
[Test]
public virtual void TestSpanOrMovesForward()
{
Spans spans = OrSpans(new string[] { "w1", "xx" });
spans.Next();
int doc = spans.Doc();
Assert.AreEqual(0, doc);
spans.SkipTo(0);
doc = spans.Doc();
// LUCENE-1583:
// according to Spans, a skipTo to the same doc or less
// should still call next() on the underlying Spans
Assert.AreEqual(1, doc);
}
[Test]
public virtual void TestSpanOrDouble()
{
Spans spans = OrSpans(new string[] { "w5", "yy" });
TstNextSpans(spans, 0, 4, 5);
TstNextSpans(spans, 2, 3, 4);
TstNextSpans(spans, 3, 4, 5);
TstNextSpans(spans, 7, 3, 4);
Assert.IsFalse(spans.Next(), "final next");
}
[Test]
public virtual void TestSpanOrDoubleSkip()
{
Spans spans = OrSpans(new string[] { "w5", "yy" });
Assert.IsTrue(spans.SkipTo(3), "initial skipTo");
Assert.AreEqual(3, spans.Doc(), "doc");
Assert.AreEqual(4, spans.Start(), "start");
Assert.AreEqual(5, spans.End(), "end");
TstNextSpans(spans, 7, 3, 4);
Assert.IsFalse(spans.Next(), "final next");
}
[Test]
public virtual void TestSpanOrUnused()
{
Spans spans = OrSpans(new string[] { "w5", "unusedTerm", "yy" });
TstNextSpans(spans, 0, 4, 5);
TstNextSpans(spans, 2, 3, 4);
TstNextSpans(spans, 3, 4, 5);
TstNextSpans(spans, 7, 3, 4);
Assert.IsFalse(spans.Next(), "final next");
}
[Test]
public virtual void TestSpanOrTripleSameDoc()
{
Spans spans = OrSpans(new string[] { "t1", "t2", "t3" });
TstNextSpans(spans, 11, 0, 1);
TstNextSpans(spans, 11, 1, 2);
TstNextSpans(spans, 11, 2, 3);
TstNextSpans(spans, 11, 3, 4);
TstNextSpans(spans, 11, 4, 5);
TstNextSpans(spans, 11, 5, 6);
Assert.IsFalse(spans.Next(), "final next");
}
[Test]
public virtual void TestSpanScorerZeroSloppyFreq()
{
bool ordered = true;
int slop = 1;
IndexReaderContext topReaderContext = Searcher.TopReaderContext;
IList<AtomicReaderContext> leaves = topReaderContext.Leaves;
int subIndex = ReaderUtil.SubIndex(11, leaves);
for (int i = 0, c = leaves.Count; i < c; i++)
{
AtomicReaderContext ctx = leaves[i];
Similarity sim = new DefaultSimilarityAnonymousInnerClassHelper(this);
Similarity oldSim = Searcher.Similarity;
Scorer spanScorer;
try
{
Searcher.Similarity = sim;
SpanNearQuery snq = new SpanNearQuery(new SpanQuery[] { MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2") }, slop, ordered);
spanScorer = Searcher.CreateNormalizedWeight(snq).Scorer(ctx, ((AtomicReader)ctx.Reader).LiveDocs);
}
finally
{
Searcher.Similarity = oldSim;
}
if (i == subIndex)
{
Assert.IsTrue(spanScorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "first doc");
Assert.AreEqual(spanScorer.DocID() + ctx.DocBase, 11, "first doc number");
float score = spanScorer.Score();
Assert.IsTrue(score == 0.0f, "first doc score should be zero, " + score);
}
else
{
Assert.IsTrue(spanScorer.NextDoc() == DocIdSetIterator.NO_MORE_DOCS, "no second doc");
}
}
}
private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity
{
private readonly TestSpans OuterInstance;
public DefaultSimilarityAnonymousInnerClassHelper(TestSpans outerInstance)
{
this.OuterInstance = outerInstance;
}
public override float SloppyFreq(int distance)
{
return 0.0f;
}
}
// LUCENE-1404
private void AddDoc(IndexWriter writer, string id, string text)
{
Document doc = new Document();
doc.Add(NewStringField("id", id, Field.Store.YES));
doc.Add(NewTextField("text", text, Field.Store.YES));
writer.AddDocument(doc);
}
// LUCENE-1404
private int HitCount(IndexSearcher searcher, string word)
{
return searcher.Search(new TermQuery(new Term("text", word)), 10).TotalHits;
}
// LUCENE-1404
private SpanQuery CreateSpan(string value)
{
return new SpanTermQuery(new Term("text", value));
}
// LUCENE-1404
private SpanQuery CreateSpan(int slop, bool ordered, SpanQuery[] clauses)
{
return new SpanNearQuery(clauses, slop, ordered);
}
// LUCENE-1404
private SpanQuery CreateSpan(int slop, bool ordered, string term1, string term2)
{
return CreateSpan(slop, ordered, new SpanQuery[] { CreateSpan(term1), CreateSpan(term2) });
}
// LUCENE-1404
[Test]
public virtual void TestNPESpanQuery()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
// Add documents
AddDoc(writer, "1", "the big dogs went running to the market");
AddDoc(writer, "2", "the cat chased the mouse, then the cat ate the mouse quickly");
// Commit
writer.Dispose();
// Get searcher
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = NewSearcher(reader);
// Control (make sure docs indexed)
Assert.AreEqual(2, HitCount(searcher, "the"));
Assert.AreEqual(1, HitCount(searcher, "cat"));
Assert.AreEqual(1, HitCount(searcher, "dogs"));
Assert.AreEqual(0, HitCount(searcher, "rabbit"));
// this throws exception (it shouldn't)
Assert.AreEqual(1, searcher.Search(CreateSpan(0, true, new SpanQuery[] { CreateSpan(4, false, "chased", "cat"), CreateSpan("ate") }), 10).TotalHits);
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestSpanNots()
{
Assert.AreEqual(0, SpanCount("s2", "s2", 0, 0), 0, "SpanNotIncludeExcludeSame1");
Assert.AreEqual(0, SpanCount("s2", "s2", 10, 10), 0, "SpanNotIncludeExcludeSame2");
//focus on behind
Assert.AreEqual(1, SpanCount("s2", "s1", 6, 0), "SpanNotS2NotS1_6_0");
Assert.AreEqual(2, SpanCount("s2", "s1", 5, 0), "SpanNotS2NotS1_5_0");
Assert.AreEqual(3, SpanCount("s2", "s1", 3, 0), "SpanNotS2NotS1_3_0");
Assert.AreEqual(4, SpanCount("s2", "s1", 2, 0), "SpanNotS2NotS1_2_0");
Assert.AreEqual(4, SpanCount("s2", "s1", 0, 0), "SpanNotS2NotS1_0_0");
//focus on both
Assert.AreEqual(2, SpanCount("s2", "s1", 3, 1), "SpanNotS2NotS1_3_1");
Assert.AreEqual(3, SpanCount("s2", "s1", 2, 1), "SpanNotS2NotS1_2_1");
Assert.AreEqual(3, SpanCount("s2", "s1", 1, 1), "SpanNotS2NotS1_1_1");
Assert.AreEqual(0, SpanCount("s2", "s1", 10, 10), "SpanNotS2NotS1_10_10");
//focus on ahead
Assert.AreEqual(0, SpanCount("s1", "s2", 10, 10), "SpanNotS1NotS2_10_10");
Assert.AreEqual(3, SpanCount("s1", "s2", 0, 1), "SpanNotS1NotS2_0_1");
Assert.AreEqual(3, SpanCount("s1", "s2", 0, 2), "SpanNotS1NotS2_0_2");
Assert.AreEqual(2, SpanCount("s1", "s2", 0, 3), "SpanNotS1NotS2_0_3");
Assert.AreEqual(1, SpanCount("s1", "s2", 0, 4), "SpanNotS1NotS2_0_4");
Assert.AreEqual(0, SpanCount("s1", "s2", 0, 8), "SpanNotS1NotS2_0_8");
//exclude doesn't exist
Assert.AreEqual(3, SpanCount("s1", "s3", 8, 8), "SpanNotS1NotS3_8_8");
//include doesn't exist
Assert.AreEqual(0, SpanCount("s3", "s1", 8, 8), "SpanNotS3NotS1_8_8");
}
private int SpanCount(string include, string exclude, int pre, int post)
{
SpanTermQuery iq = new SpanTermQuery(new Term(field, include));
SpanTermQuery eq = new SpanTermQuery(new Term(field, exclude));
SpanNotQuery snq = new SpanNotQuery(iq, eq, pre, post);
Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, snq);
int i = 0;
while (spans.Next())
{
i++;
}
return i;
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System.IO;
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Soomla.Store
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
/// <summary>
/// This class holds the store's configurations.
/// </summary>
public class StoreSettings : ISoomlaSettings
{
#if UNITY_EDITOR
static StoreSettings instance = new StoreSettings();
static StoreSettings()
{
SoomlaEditorScript.addSettings(instance);
}
bool showAndroidSettings = (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android);
bool showIOSSettings = (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iPhone);
GUIContent noneBPLabel = new GUIContent("You have your own Billing Service");
GUIContent playLabel = new GUIContent("Google Play");
GUIContent amazonLabel = new GUIContent("Amazon");
GUIContent bazaarLabel = new GUIContent("Bazaar");
GUIContent publicKeyLabel = new GUIContent("API Key [?]:", "The API key from Google Play dev console (just in case you're using Google Play as billing provider).");
GUIContent bazaar_publicKeyLabel = new GUIContent("API Key [?]:", "The API key from Bazaar dev console (just in case you're using Bazaar as billing provider).");
GUIContent testPurchasesLabel = new GUIContent("Test Purchases [?]:", "Check if you want to allow purchases of Google's test product ids.");
GUIContent bazaar_testPurchasesLabel = new GUIContent("Test Purchases [?]:", "Check if you want to allow purchases of Bazaar's test product ids.");
GUIContent packageNameLabel = new GUIContent("Package Name [?]", "Your package as defined in Unity.");
GUIContent iosSsvLabel = new GUIContent("Receipt Validation [?]:", "Check if you want your purchases validated with SOOMLA Server Side Protection Service.");
public void OnEnable() {
// Generating AndroidManifest.xml
// ManifestTools.GenerateManifest();
}
public void OnModuleGUI() {
AndroidGUI();
EditorGUILayout.Space();
IOSGUI();
}
public void OnInfoGUI() {
}
public void OnSoomlaGUI() {
}
private void IOSGUI()
{
showIOSSettings = EditorGUILayout.Foldout(showIOSSettings, "iOS Build Settings");
if (showIOSSettings)
{
IosSSV = EditorGUILayout.Toggle(iosSsvLabel, IosSSV);
}
EditorGUILayout.Space();
}
private void AndroidGUI()
{
showAndroidSettings = EditorGUILayout.Foldout(showAndroidSettings, "Android Settings");
if (showAndroidSettings)
{
EditorGUILayout.BeginHorizontal();
SoomlaEditorScript.SelectableLabelField(packageNameLabel, PlayerSettings.bundleIdentifier);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Billing Service Selection", MessageType.None);
if (!GPlayBP && !AmazonBP && !BazaarBP && !NoneBP) {
GPlayBP = true;
}
NoneBP = EditorGUILayout.Toggle(noneBPLabel, NoneBP);
bool update;
bpUpdate.TryGetValue("none", out update);
if (NoneBP && !update) {
setCurrentBPUpdate("none");
AmazonBP = false;
GPlayBP = false;
BazaarBP = false;
SoomlaManifestTools.GenerateManifest();
handlePlayBPJars(true);
handleAmazonBPJars(true);
handleBazaarBPJars(true);
}
GPlayBP = EditorGUILayout.Toggle(playLabel, GPlayBP);
if (GPlayBP) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField(publicKeyLabel, SoomlaEditorScript.FieldWidth, SoomlaEditorScript.FieldHeight);
AndroidPublicKey = EditorGUILayout.TextField(AndroidPublicKey, SoomlaEditorScript.FieldHeight);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(SoomlaEditorScript.EmptyContent, SoomlaEditorScript.SpaceWidth, SoomlaEditorScript.FieldHeight);
AndroidTestPurchases = EditorGUILayout.Toggle(testPurchasesLabel, AndroidTestPurchases);
EditorGUILayout.EndHorizontal();
}
bpUpdate.TryGetValue("play", out update);
if (GPlayBP && !update) {
setCurrentBPUpdate("play");
AmazonBP = false;
NoneBP = false;
BazaarBP = false;
SoomlaManifestTools.GenerateManifest();
handlePlayBPJars(false);
handleAmazonBPJars(true);
handleBazaarBPJars(true);
}
BazaarBP = EditorGUILayout.Toggle(bazaarLabel, BazaarBP);
if (BazaarBP) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField(bazaar_publicKeyLabel, SoomlaEditorScript.FieldWidth, SoomlaEditorScript.FieldHeight);
BazaarPublicKey = EditorGUILayout.TextField(BazaarPublicKey, SoomlaEditorScript.FieldHeight);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(SoomlaEditorScript.EmptyContent, SoomlaEditorScript.SpaceWidth, SoomlaEditorScript.FieldHeight);
BazaarTestPurchases = EditorGUILayout.Toggle(bazaar_testPurchasesLabel, BazaarTestPurchases);
EditorGUILayout.EndHorizontal();
}
bpUpdate.TryGetValue("bazaar", out update);
if (BazaarBP && !update) {
setCurrentBPUpdate("bazaar");
AmazonBP = false;
NoneBP = false;
GPlayBP = false;
SoomlaManifestTools.GenerateManifest();
handleBazaarBPJars(false);
handlePlayBPJars(true);
handleAmazonBPJars(true);
}
AmazonBP = EditorGUILayout.Toggle(amazonLabel, AmazonBP);
bpUpdate.TryGetValue("amazon", out update);
if (AmazonBP && !update) {
setCurrentBPUpdate("amazon");
GPlayBP = false;
NoneBP = false;
BazaarBP = false;
SoomlaManifestTools.GenerateManifest();
handlePlayBPJars(true);
handleAmazonBPJars(false);
handleBazaarBPJars(true);
}
}
EditorGUILayout.Space();
}
/** Billing Providers util functions **/
private void setCurrentBPUpdate(string bpKey) {
bpUpdate[bpKey] = true;
var buffer = new List<string>(bpUpdate.Keys);
foreach(string key in buffer) {
if (key != bpKey) {
bpUpdate[key] = false;
}
}
}
private Dictionary<string, bool> bpUpdate = new Dictionary<string, bool>();
private static string bpRootPath = Application.dataPath + "/Soomla/compilations/android-billing-services/";
public static void handlePlayBPJars(bool remove) {
try {
if (remove) {
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreGooglePlay.jar");
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreGooglePlay.jar.meta");
} else {
FileUtil.CopyFileOrDirectory(bpRootPath + "google-play/AndroidStoreGooglePlay.jar",
Application.dataPath + "/Plugins/Android/AndroidStoreGooglePlay.jar");
}
}catch {}
}
public static void handleBazaarBPJars(bool remove) {
try {
if (remove) {
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreBazaar.jar");
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreBazaar.jar.meta");
} else {
FileUtil.CopyFileOrDirectory(bpRootPath + "bazaar/AndroidStoreBazaar.jar",
Application.dataPath + "/Plugins/Android/AndroidStoreBazaar.jar");
}
}catch {}
}
public static void handleAmazonBPJars(bool remove) {
try {
if (remove) {
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreAmazon.jar");
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/AndroidStoreAmazon.jar.meta");
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/in-app-purchasing-1.0.3.jar");
FileUtil.DeleteFileOrDirectory(Application.dataPath + "/Plugins/Android/in-app-purchasing-1.0.3.jar.meta");
} else {
FileUtil.CopyFileOrDirectory(bpRootPath + "amazon/AndroidStoreAmazon.jar",
Application.dataPath + "/Plugins/Android/AndroidStoreAmazon.jar");
FileUtil.CopyFileOrDirectory(bpRootPath + "amazon/in-app-purchasing-1.0.3.jar",
Application.dataPath + "/Plugins/Android/in-app-purchasing-1.0.3.jar");
}
}catch {}
}
#endif
/** Store Specific Variables **/
public static string AND_PUB_KEY_DEFAULT = "YOUR GOOGLE PLAY PUBLIC KEY";
public static string AndroidPublicKey
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AndroidPublicKey", out value) ? value : AND_PUB_KEY_DEFAULT;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AndroidPublicKey", out v);
if (v != value)
{
SoomlaEditorScript.Instance.setSettingsValue("AndroidPublicKey",value);
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool AndroidTestPurchases
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AndroidTestPurchases", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AndroidTestPurchases", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("AndroidTestPurchases",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static string BAZAAR_PUB_KEY_DEFAULT = "YOUR BAZAAR RSA KEY";
public static string BazaarPublicKey
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarPublicKey", out value) ? value : BAZAAR_PUB_KEY_DEFAULT;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarPublicKey", out v);
if (v != value)
{
SoomlaEditorScript.Instance.setSettingsValue("BazaarPublicKey",value);
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool BazaarTestPurchases
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarTestPurchases", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarTestPurchases", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("BazaarTestPurchases",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool IosSSV
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("IosSSV", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("IosSSV", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("IosSSV",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool NoneBP
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("NoneBP", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("NoneBP", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("NoneBP",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool GPlayBP
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("GPlayBP", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("GPlayBP", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("GPlayBP",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool AmazonBP
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AmazonBP", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("AmazonBP", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("AmazonBP",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
public static bool BazaarBP
{
get {
string value;
return SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarBP", out value) ? Convert.ToBoolean(value) : false;
}
set
{
string v;
SoomlaEditorScript.Instance.SoomlaSettings.TryGetValue("BazaarBP", out v);
if (Convert.ToBoolean(v) != value)
{
SoomlaEditorScript.Instance.setSettingsValue("BazaarBP",value.ToString());
SoomlaEditorScript.DirtyEditor ();
}
}
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Diagnostics;
namespace Oranikle.Report.Engine
{
/// <summary>
/// The PageTree object contains references to all the pages used within the Pdf.
/// All individual pages are referenced through the kids string
/// </summary>
public class PdfPageTree:PdfBase
{
private string pageTree;
private string kids;
private int MaxPages;
public PdfPageTree(PdfAnchor pa):base(pa)
{
kids="[ ";
MaxPages=0;
}
/// <summary>
/// Add a page to the Page Tree. ObjNum is the object number of the page to be added.
/// pageNum is the page number of the page.
/// </summary>
/// <param name="objNum"></param>
public void AddPage(int objNum)
{
Debug.Assert(objNum >= 0 && objNum <= this.Current);
MaxPages++;
string refPage=objNum+" 0 R ";
kids=kids+refPage;
}
/// <summary>
/// returns the Page Tree Dictionary
/// </summary>
/// <returns></returns>
public byte[] GetPageTree(long filePos,out int size)
{
pageTree=string.Format("\r\n{0} 0 obj<</Count {1}/Kids {2}]>> endobj\t",
this.objectNum,MaxPages,kids);
return this.GetUTF8Bytes(pageTree,filePos,out size);
}
}
/// <summary>
/// This class represents individual pages within the pdf.
/// The contents of the page belong to this class
/// </summary>
public class PdfPage:PdfBase
{
private string page;
private string pageSize;
private string fontRef;
private string imageRef;
private string patternRef;
private string colorSpaceRef;
private string resourceDict,contents;
private string annotsDict;
public PdfPage(PdfAnchor pa):base(pa)
{
resourceDict=null;
contents=null;
pageSize=null;
fontRef=null;
imageRef=null;
annotsDict=null;
colorSpaceRef=null;
patternRef=null;
}
/// <summary>
/// Create The Pdf page
/// </summary>
public void CreatePage(int refParent,PdfPageSize pSize)
{
pageSize=string.Format("[0 0 {0} {1}]",pSize.xWidth,pSize.yHeight);
page=string.Format("\r\n{0} 0 obj<</Type /Page/Parent {1} 0 R/Rotate 0/MediaBox {2}/CropBox {2}",
this.objectNum,refParent,pageSize);
}
public void AddHyperlink(float x, float y, float height, float width, string url)
{
if (annotsDict == null)
annotsDict = "\r/Annots [";
annotsDict += string.Format(@"<</Type /Annot /Subtype /Link /Rect [{0} {1} {2} {3}] /Border [0 0 0] /A <</S /URI /URI ({4})>>>>",
x, y, x+width, y-height, url);
}
public void AddToolTip(float x, float y, float height, float width, string tooltip)
{
if (annotsDict == null)
annotsDict = "\r/Annots [";
annotsDict += string.Format(@"<</Type /Annot /Rect [{0} {1} {2} {3}] /Border [0 0 0] /IC [1.0 1.0 0.666656] /CA 0.00500488 /C [1.0 0.0 0.0] /Name/Comment /T(Value) /Contents({4}) /F 288 /Subtype/Square>>", /*/A <</S /URI /URI ({4})>>*/
x, y, x + width, y - height, tooltip);
}
/// <summary>
/// Add Pattern Resources to the pdf page
/// </summary>
public void AddResource(PdfPattern patterns,int contentRef)
{
foreach (PdfPatternEntry pat in patterns.Patterns.Values)
{
patternRef+=string.Format("/{0} {1} 0 R",pat.pattern,pat.objectNum);
}
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
/// <summary>
/// Add Font Resources to the pdf page
/// </summary>
public void AddResource(PdfFonts fonts,int contentRef)
{
foreach (PdfFontEntry font in fonts.Fonts.Values)
{
fontRef+=string.Format("/{0} {1} 0 R",font.font,font.objectNum);
}
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
public void AddResource(PatternObj po,int contentRef)
{
colorSpaceRef=string.Format("/CS1 {0} 0 R",po.objectNum);
}
/// <summary>
/// Add Image Resources to the pdf page
/// </summary>
public void AddResource(PdfImageEntry ie,int contentRef)
{
if (imageRef == null || imageRef.IndexOf("/"+ie.name) < 0) // only need it once per page
// imageRef+=string.Format("/XObject << /{0} {1} 0 R >>",ie.name,ie.objectNum);
imageRef+=string.Format("/{0} {1} 0 R ",ie.name,ie.objectNum);
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
/// <summary>
/// Get the Page Dictionary to be written to the file
/// </summary>
/// <returns></returns>
public byte[] GetPageDict(long filePos,out int size)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//will need to add pattern here
sb.AppendFormat("/Resources<<\r\n/Font<<{0}>>",fontRef);
if (patternRef != null)
sb.AppendFormat("\r\n/Pattern <<{0}>>",patternRef);
if (colorSpaceRef != null)
sb.AppendFormat("\r\n/ColorSpace <<{0}>>",colorSpaceRef);
sb.Append("\r\n/ProcSet[/PDF/Text");
if (imageRef == null)
sb.Append("]>>");
else
sb.AppendFormat("\r\n/ImageB]/XObject <<{0}>>>>",imageRef);
resourceDict = sb.ToString();
//if (imageRef == null)
// resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text]>>",fontRef);
//else
// resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text/ImageB]/XObject <<{1}>>>>",fontRef, imageRef);
if (annotsDict != null)
page += (annotsDict+"]\r");
page+=resourceDict+"\r\n"+contents+">>\r\nendobj\r\n";
return this.GetUTF8Bytes(page,filePos,out size);
}
}
/// <summary>
/// Specify the page size in 1/72 inches units.
/// </summary>
public struct PdfPageSize
{
public int xWidth;
public int yHeight;
public int leftMargin;
public int rightMargin;
public int topMargin;
public int bottomMargin;
public PdfPageSize(int width,int height)
{
xWidth=width;
yHeight=height;
leftMargin=0;
rightMargin=0;
topMargin=0;
bottomMargin=0;
}
public void SetMargins(int L,int T,int R,int B)
{
leftMargin=L;
rightMargin=R;
topMargin=T;
bottomMargin=B;
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
#if !READ_ONLY
using System;
using System.Collections.Generic;
using SquabPie.Mono.Collections.Generic;
using SR = System.Reflection;
using SquabPie.Mono.Cecil.Metadata;
namespace SquabPie.Mono.Cecil {
#if !READ_ONLY
public interface IMetadataImporterProvider {
IMetadataImporter GetMetadataImporter (ModuleDefinition module);
}
public interface IMetadataImporter {
TypeReference ImportReference (TypeReference type, IGenericParameterProvider context);
FieldReference ImportReference (FieldReference field, IGenericParameterProvider context);
MethodReference ImportReference (MethodReference method, IGenericParameterProvider context);
}
#if !PCL
public interface IReflectionImporterProvider {
IReflectionImporter GetReflectionImporter (ModuleDefinition module);
}
public interface IReflectionImporter {
TypeReference ImportReference (Type type, IGenericParameterProvider context);
FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context);
MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context);
}
#endif
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
if (provider == null)
throw new ArgumentNullException ("provider");
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != candidate.Name)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
public static ImportGenericContext For (IGenericParameterProvider context)
{
return context != null ? new ImportGenericContext (context) : default (ImportGenericContext);
}
}
#if !PCL
public class ReflectionImporter : IReflectionImporter {
readonly ModuleDefinition module;
public ReflectionImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
enum ImportGenericKind {
Definition,
Open,
}
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
{ typeof (TypedReference), ElementType.TypedByRef },
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type.Assembly),
type.IsValueType);
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType)
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
return type.IsNested;
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType)
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod != null)
return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition);
if (type.DeclaringType != null)
return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition);
throw new InvalidOperationException();
}
private static string NormalizedFullName (Type type)
{
if (IsNestedType (type))
return NormalizedFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType && !type.IsGenericTypeDefinition;
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
AssemblyNameReference ImportScope (SR.Assembly assembly)
{
AssemblyNameReference scope;
var name = assembly.GetName ();
if (TryGetAssemblyNameReference (name, out scope))
return scope;
scope = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.CultureInfo.Name,
PublicKeyToken = name.GetPublicKeyToken (),
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
};
module.AssemblyReferences.Add (scope);
return scope;
}
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
return field.Module.ResolveField (field.MetadataToken);
}
MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = method.Module.ResolveMethod (method.MetadataToken);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (
type,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
}
#endif
public class MetadataImporter : IMetadataImporter {
readonly ModuleDefinition module;
public MetadataImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type.Scope),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
return reference;
}
IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportAssemblyName ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
{
AssemblyNameReference reference;
if (module.TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.FnPtr:
var fnptr = (FunctionPointerType) type;
var imported_fnptr = new FunctionPointerType () {
HasThis = fnptr.HasThis,
ExplicitThis = fnptr.ExplicitThis,
CallingConvention = fnptr.CallingConvention,
ReturnType = ImportType (fnptr.ReturnType, context),
};
if (!fnptr.HasParameters)
return imported_fnptr;
for (int i = 0; i < fnptr.Parameters.Count; i++)
imported_fnptr.Parameters.Add (new ParameterDefinition (
ImportType (fnptr.Parameters [i].ParameterType, context)));
return imported_fnptr;
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var parameters = method.Parameters;
var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count);
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (type, ImportGenericContext.For (context));
}
public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method, ImportGenericContext.For (context));
}
}
static partial class Mixin {
public static void CheckModule (ModuleDefinition module)
{
if (module == null)
throw new ArgumentNullException ("module");
}
public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (!Equals (name_reference, reference))
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
private static bool Equals (byte [] a, byte [] b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a [i] != b [i])
return false;
return true;
}
private static bool Equals<T> (T a, T b) where T : class, IEquatable<T>
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
return a.Equals (b);
}
private static bool Equals (AssemblyNameReference a, AssemblyNameReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a.Name != b.Name)
return false;
if (!Equals (a.Version, b.Version))
return false;
if (a.Culture != b.Culture)
return false;
if (!Equals (a.PublicKeyToken, b.PublicKeyToken))
return false;
return true;
}
}
#endif
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The MatchCollection lists the successful matches that
// result when searching a string for a regular expression.
using System.Collections;
using System.Collections.Generic;
namespace System.Text.RegularExpressions
{
/*
* This collection returns a sequence of successful match results, either
* from GetMatchCollection() or GetExecuteCollection(). It stops when the
* first failure is encountered (it does not return the failed match).
*/
/// <summary>
/// Represents the set of names appearing as capturing group
/// names in a regular expression.
/// </summary>
public class MatchCollection : ICollection
{
internal Regex _regex;
internal List<Match> _matches;
internal bool _done;
internal String _input;
internal int _beginning;
internal int _length;
internal int _startat;
internal int _prevlen;
private static int s_infinite = 0x7FFFFFFF;
internal MatchCollection(Regex regex, String input, int beginning, int length, int startat)
{
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException("startat", SR.BeginIndexNotNegative);
_regex = regex;
_input = input;
_beginning = beginning;
_length = length;
_startat = startat;
_prevlen = -1;
_matches = new List<Match>();
_done = false;
}
internal Match GetMatch(int i)
{
if (i < 0)
return null;
if (_matches.Count > i)
return (Match)_matches[i];
if (_done)
return null;
Match match;
do
{
match = _regex.Run(false, _prevlen, _input, _beginning, _length, _startat);
if (!match.Success)
{
_done = true;
return null;
}
_matches.Add(match);
_prevlen = match._length;
_startat = match._textpos;
} while (_matches.Count <= i);
return match;
}
private void EnsureInitialized()
{
if (!_done)
{
GetMatch(s_infinite);
}
}
/// <summary>
/// Returns the number of captures.
/// </summary>
public int Count
{
get
{
EnsureInitialized();
return _matches.Count;
}
}
Object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Returns the ith Match in the collection.
/// </summary>
public virtual Match this[int i]
{
get
{
Match match;
match = GetMatch(i);
if (match == null)
throw new ArgumentOutOfRangeException("i");
return match;
}
}
/// <summary>
/// Copies all the elements of the collection to the given array
/// starting at the given index.
/// </summary>
void ICollection.CopyTo(Array array, int arrayIndex)
{
EnsureInitialized();
((ICollection)_matches).CopyTo(array, arrayIndex);
}
/// <summary>
/// Provides an enumerator in the same order as Item[i].
/// </summary>
public IEnumerator GetEnumerator()
{
return new MatchEnumerator(this);
}
}
/*
* This non-public enumerator lists all the group matches.
* Should it be public?
*/
internal class MatchEnumerator : IEnumerator
{
internal MatchCollection _matchcoll;
internal Match _match = null;
internal int _curindex;
internal bool _done;
/*
* Nonpublic constructor
*/
internal MatchEnumerator(MatchCollection matchcoll)
{
_matchcoll = matchcoll;
}
/*
* Advance to the next match
*/
public bool MoveNext()
{
if (_done)
return false;
_match = _matchcoll.GetMatch(_curindex);
_curindex++;
if (_match == null)
{
_done = true;
return false;
}
return true;
}
/*
* The current match
*/
public Object Current
{
get
{
if (_match == null)
throw new InvalidOperationException(SR.EnumNotStarted);
return _match;
}
}
/*
* Position before the first item
*/
public void Reset()
{
_curindex = 0;
_done = false;
_match = null;
}
}
}
| |
using System.Reflection;
using UnityEngine;
namespace Stratus
{
/// <summary>
/// A type of action that modifies the value of
/// a given property over a specified amount of time, using a specified
/// interpolation formula(Ease).
/// </summary>
public abstract class StratusActionProperty : StratusAction
{
/// <summary>
/// The supported types for this interpolator
/// </summary>
public enum Types
{
Integer,
Float,
Boolean,
Vector2,
Vector3,
Vector4,
Color,
None
}
/// <summary>
/// The types supported by this interpolator
/// </summary>
public static System.Type[] supportedTypes { get; } = new System.Type[7] { typeof(float), typeof(int), typeof(bool), typeof(Vector2), typeof(Vector3), typeof(Color), typeof(Vector4) };
/// <summary>
/// Deduces if the given type is one of the supported ones
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Types Deduce(System.Type type)
{
if (type == typeof(int))
{
return Types.Integer;
}
else if (type == typeof(float))
{
return Types.Float;
}
else if (type == typeof(bool))
{
return Types.Boolean;
}
else if (type == typeof(Vector2))
{
return Types.Vector2;
}
else if (type == typeof(Vector3))
{
return Types.Vector3;
}
else if (type == typeof(Vector4))
{
return Types.Vector4;
}
else if (type == typeof(Color))
{
return Types.Color;
}
return Types.None;
}
protected StratusEase easeType;
/// <summary>
/// Constructor
/// </summary>
/// <param name="duration">How long should the action delay for</param>
/// <param name="ease">The interpolation algorithm to use</param>
public StratusActionProperty(float duration, StratusEase ease)
{
this.duration = duration;
this.easeType = ease;
}
/// <summary>
/// Updates the action
/// </summary>
/// <param name="dt">The delta time</param>
/// <returns>How much time was consumed during this action</returns>
public override float Update(float dt)
{
return this.Interpolate(dt);
}
public abstract float Interpolate(float dt);
}
public abstract class StratusActionPropertyBase<T> : StratusActionProperty
{
//----------------------------------------------------------------------/
// Fields
//----------------------------------------------------------------------/
protected T difference;
protected T initialValue;
protected T endValue;
private bool initialized = false;
protected object target;
protected PropertyInfo property;
protected FieldInfo field;
//----------------------------------------------------------------------/
// CTOR
//----------------------------------------------------------------------/
public StratusActionPropertyBase(object target, PropertyInfo property, T endValue, float duration, StratusEase ease)
: base(duration, ease)
{
this.target = target;
this.property = property;
this.endValue = endValue;
base.duration = duration;
this.easeType = ease;
}
public StratusActionPropertyBase(object target, FieldInfo field, T endValue, float duration, StratusEase ease)
: base(duration, ease)
{
this.target = target;
this.field = field;
this.endValue = endValue;
base.duration = duration;
this.easeType = ease;
}
/// <summary>
/// Interpolates the given Property/Field.
/// </summary>
/// <param name="dt">The current delta time.</param>
/// <returns></returns>
public override float Interpolate(float dt)
{
if (!this.initialized)
{
this.Initialize();
}
this.elapsed += dt;
float timeLeft = this.duration - this.elapsed;
// If done updating
if (timeLeft <= dt)
{
this.isFinished = true;
this.SetLast();
return dt;
}
this.SetCurrent();
return timeLeft;
}
/// <summary>
/// Gets the initial value for the property. This is done separately
/// because we want to capture the value at the time this action is beinig
/// executed, not when it was created!
/// </summary>
public void Initialize()
{
if (this.property != null)
{
this.initialValue = (T)this.property.GetValue(this.target, null);
}
else if (this.field != null)
{
this.initialValue = (T)this.field.GetValue(this.target);
}
else
{
throw new System.Exception("Couldn't set initial value!");
}
// Now we can compute the difference
this.ComputeDifference();
if (logging)
{
StratusDebug.Log("InitialValue = '" + this.initialValue
+ "', EndValue = '" + this.endValue + "'"
+ "' Difference = '" + this.difference + "'");
}
this.initialized = true;
}
/// <summary>
/// Sets the current value for the property.
/// </summary>
public virtual void SetCurrent()
{
float easeVal = this.easeType.Evaluate(this.elapsed / this.duration);
T currentValue = this.ComputeCurrentValue((easeVal));
if (logging)
{
StratusDebug.Log("CurrentValue = '" + currentValue + "'");
}
this.Set(currentValue);
}
/// <summary>
/// Sets the last value for the property.
/// </summary>
public virtual void SetLast()
{
this.Set(this.endValue);
}
/// <summary>
/// Sets the value for the property.
/// </summary>
/// <param name="val"></param>
public void Set(T val)
{
if (this.property != null)
{
this.property.SetValue(this.target, val, null);
}
else
{
this.field.SetValue(this.target, val);
}
}
public abstract void ComputeDifference();
public abstract T ComputeCurrentValue(float easeVal);
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Atom;
using Microsoft.Data.OData.Json;
#endregion Namespaces
/// <summary>
/// Base class for all input contexts, defines the interface
/// to be implemented by the specific formats.
/// </summary>
internal abstract class ODataInputContext : IDisposable
{
/// <summary>The format for this input context.</summary>
private readonly ODataFormat format;
/// <summary>The message reader settings to be used for reading.</summary>
private readonly ODataMessageReaderSettings messageReaderSettings;
/// <summary>The protocol version to use when reading the payload.</summary>
private readonly ODataVersion version;
/// <summary>Set to true if this context is reading a response payload.</summary>
private readonly bool readingResponse;
/// <summary>true if the input should be read synchronously; false if it should be read asynchronously.</summary>
private readonly bool synchronous;
/// <summary>The model to use.</summary>
private readonly IEdmModel model;
/// <summary>The optional URL resolver to perform custom URL resolution for URLs read from the payload.</summary>
private readonly IODataUrlResolver urlResolver;
/// <summary>Set to true if the input was disposed.</summary>
private bool disposed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="format">The format for this input context.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="synchronous">true if the input should be read synchronously; false if it should be read asynchronously.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
protected ODataInputContext(
ODataFormat format,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
bool synchronous,
IEdmModel model,
IODataUrlResolver urlResolver)
{
ExceptionUtils.CheckArgumentNotNull(format, "format");
ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
this.format = format;
this.messageReaderSettings = messageReaderSettings;
this.version = version;
this.readingResponse = readingResponse;
this.synchronous = synchronous;
this.model = model;
this.urlResolver = urlResolver;
}
/// <summary>
/// The message reader settings to be used for reading.
/// </summary>
internal ODataMessageReaderSettings MessageReaderSettings
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.messageReaderSettings;
}
}
/// <summary>
/// The version of the OData protocol to use.
/// </summary>
internal ODataVersion Version
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.version;
}
}
/// <summary>
/// Set to true if a response is being read.
/// </summary>
internal bool ReadingResponse
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.readingResponse;
}
}
/// <summary>
/// true if the input should be read synchronously; false if it should be read asynchronously.
/// </summary>
internal bool Synchronous
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.synchronous;
}
}
/// <summary>
/// The model to use or null if no metadata is available.
/// </summary>
internal IEdmModel Model
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.model;
}
}
/// <summary>
/// The optional URL resolver to perform custom URL resolution for URLs read from the payload.
/// </summary>
internal IODataUrlResolver UrlResolver
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.urlResolver;
}
}
/// <summary>
/// true if the WCF DS client compatibility format behavior should be used; otherwise false.
/// </summary>
protected internal bool UseClientFormatBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesClient;
}
}
/// <summary>
/// true if the WCF DS server compatibility format behavior should be used; otherwise false.
/// </summary>
protected internal bool UseServerFormatBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesServer;
}
}
/// <summary>
/// true if the default format behavior should be used; otherwise false.
/// </summary>
protected internal bool UseDefaultFormatBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.FormatBehaviorKind == ODataBehaviorKind.Default;
}
}
/// <summary>
/// true if the WCF DS client compatibility API behavior should be used; otherwise false.
/// </summary>
protected internal bool UseClientApiBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.ApiBehaviorKind == ODataBehaviorKind.WcfDataServicesClient;
}
}
/// <summary>
/// true if the WCF DS server compatibility API behavior should be used; otherwise false.
/// </summary>
protected internal bool UseServerApiBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.ApiBehaviorKind == ODataBehaviorKind.WcfDataServicesServer;
}
}
/// <summary>
/// true if the default API behavior should be used; otherwise false.
/// </summary>
protected internal bool UseDefaultApiBehavior
{
get
{
return this.messageReaderSettings.ReaderBehavior.ApiBehaviorKind == ODataBehaviorKind.Default;
}
}
/// <summary>
/// IDisposable.Dispose() implementation to cleanup unmanaged resources of the context.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates an instance of the input context for the specified format.
/// </summary>
/// <param name="format">The format to create the context for.</param>
/// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
/// <param name="message">The message to use.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
/// <returns>The newly created input context.</returns>
internal static ODataInputContext CreateInputContext(
ODataFormat format,
ODataPayloadKind readerPayloadKind,
ODataMessage message,
Encoding encoding,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
IEdmModel model,
IODataUrlResolver urlResolver)
{
DebugUtils.CheckNoExternalCallers();
if (format == ODataFormat.Atom)
{
return ODataAtomInputContext.Create(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver);
}
if (format == ODataFormat.VerboseJson)
{
return ODataJsonInputContext.Create(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver);
}
if (format == ODataFormat.Metadata)
{
return ODataMetadataInputContext.Create(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver);
}
if (format == ODataFormat.Batch || format == ODataFormat.RawValue)
{
return ODataRawInputContext.Create(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver,
readerPayloadKind);
}
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataInputContext_CreateInputContext_UnrecognizedFormat));
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously creates an instance of the input context for the specified format.
/// </summary>
/// <param name="format">The format to create the context for.</param>
/// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
/// <param name="message">The message to use.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
/// <returns>Task which when completed returned the newly created input context.</returns>
internal static Task<ODataInputContext> CreateInputContextAsync(
ODataFormat format,
ODataPayloadKind readerPayloadKind,
ODataMessage message,
Encoding encoding,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
IEdmModel model,
IODataUrlResolver urlResolver)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(format != ODataFormat.Metadata, "Async reading of metadata documents is not supported.");
Debug.Assert(readerPayloadKind != ODataPayloadKind.MetadataDocument, "Async reading of metadata documents is not supported.");
if (format == ODataFormat.Atom)
{
return ODataAtomInputContext.CreateAsync(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver);
}
if (format == ODataFormat.VerboseJson)
{
return ODataJsonInputContext.CreateAsync(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver);
}
if (format == ODataFormat.Batch || format == ODataFormat.RawValue)
{
return ODataRawInputContext.CreateAsync(
format,
message,
encoding,
messageReaderSettings,
version,
readingResponse,
model,
urlResolver,
readerPayloadKind);
}
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataInputContext_CreateInputContext_UnrecognizedFormat));
}
#endif
/// <summary>
/// Creates an <see cref="ODataReader" /> to read a feed.
/// </summary>
/// <param name="expectedBaseEntityType">The expected base entity type for the entries in the feed.</param>
/// <returns>The newly created <see cref="ODataReader"/>.</returns>
internal virtual ODataReader CreateFeedReader(IEdmEntityType expectedBaseEntityType)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Feed);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously creates an <see cref="ODataReader" /> to read a feed.
/// </summary>
/// <param name="expectedBaseEntityType">The expected base entity type for the entries in the feed.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataReader"/>.</returns>
internal virtual Task<ODataReader> CreateFeedReaderAsync(IEdmEntityType expectedBaseEntityType)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Feed);
}
#endif
/// <summary>
/// Creates an <see cref="ODataReader" /> to read an entry.
/// </summary>
/// <param name="expectedEntityType">The expected entity type for the entry to be read.</param>
/// <returns>The newly created <see cref="ODataReader"/>.</returns>
internal virtual ODataReader CreateEntryReader(IEdmEntityType expectedEntityType)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Entry);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously creates an <see cref="ODataReader" /> to read an entry.
/// </summary>
/// <param name="expectedEntityType">The expected entity type for the entry to be read.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataReader"/>.</returns>
internal virtual Task<ODataReader> CreateEntryReaderAsync(IEdmEntityType expectedEntityType)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Entry);
}
#endif
/// <summary>
/// Create a <see cref="ODataCollectionReader"/>.
/// </summary>
/// <param name="expectedItemTypeReference">The expected type reference for the items in the collection.</param>
/// <returns>The newly created <see cref="ODataCollectionReader"/>.</returns>
internal virtual ODataCollectionReader CreateCollectionReader(IEdmTypeReference expectedItemTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Collection);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously create a <see cref="ODataCollectionReader"/>.
/// </summary>
/// <param name="expectedItemTypeReference">The expected type reference for the items in the collection.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataCollectionReader"/>.</returns>
internal virtual Task<ODataCollectionReader> CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Collection);
}
#endif
/// <summary>
/// Create a <see cref="ODataBatchReader"/>.
/// </summary>
/// <param name="batchBoundary">The batch boundary to use.</param>
/// <returns>The newly created <see cref="ODataBatchReader"/>.</returns>
/// <remarks>
/// Since we don't want to support batch format extensibility (at least not yet) this method should remain internal.
/// </remarks>
internal virtual ODataBatchReader CreateBatchReader(string batchBoundary)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Batch);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously create a <see cref="ODataBatchReader"/>.
/// </summary>
/// <param name="batchBoundary">The batch boundary to use.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataBatchReader"/>.</returns>
/// <remarks>
/// Since we don't want to support batch format extensibility (at least not yet) this method should remain internal.
/// </remarks>
internal virtual Task<ODataBatchReader> CreateBatchReaderAsync(string batchBoundary)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Batch);
}
#endif
/// <summary>
/// Create a <see cref="ODataParameterReader"/>.
/// </summary>
/// <param name="functionImport">The function import whose parameters are being read.</param>
/// <returns>The newly created <see cref="ODataParameterReader"/>.</returns>
internal virtual ODataParameterReader CreateParameterReader(IEdmFunctionImport functionImport)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Parameter);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously create a <see cref="ODataParameterReader"/>.
/// </summary>
/// <param name="functionImport">The function import whose parameters are being read.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataParameterReader"/>.</returns>
internal virtual Task<ODataParameterReader> CreateParameterReaderAsync(IEdmFunctionImport functionImport)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Parameter);
}
#endif
/// <summary>
/// Read a service document.
/// This method reads the service document from the input and returns
/// an <see cref="ODataWorkspace"/> that represents the read service document.
/// </summary>
/// <returns>An <see cref="ODataWorkspace"/> representing the read service document.</returns>
internal virtual ODataWorkspace ReadServiceDocument()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ServiceDocument);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a service document.
/// This method reads the service document from the input and returns
/// an <see cref="ODataWorkspace"/> that represents the read service document.
/// </summary>
/// <returns>Task which when completed returns an <see cref="ODataWorkspace"/> representing the read service document.</returns>
internal virtual Task<ODataWorkspace> ReadServiceDocumentAsync()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ServiceDocument);
}
#endif
/// <summary>
/// Read a metadata document.
/// This method reads the metadata document from the input and returns
/// an <see cref="IEdmModel"/> that represents the read metadata document.
/// </summary>
/// <returns>An <see cref="IEdmModel"/> representing the read metadata document.</returns>
internal virtual IEdmModel ReadMetadataDocument()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.MetadataDocument);
}
/// <summary>
/// Read the property from the input and
/// return an <see cref="ODataProperty"/> representing the read property.
/// </summary>
/// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
/// <returns>An <see cref="ODataProperty"/> representing the read property.</returns>
internal virtual ODataProperty ReadProperty(IEdmTypeReference expectedPropertyTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read the property from the input and
/// return an <see cref="ODataProperty"/> representing the read property.
/// </summary>
/// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
/// <returns>Task which when completed returns an <see cref="ODataProperty"/> representing the read property.</returns>
internal virtual Task<ODataProperty> ReadPropertyAsync(IEdmTypeReference expectedPropertyTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
}
#endif
/// <summary>
/// Read a top-level error.
/// </summary>
/// <returns>An <see cref="ODataError"/> representing the read error.</returns>
internal virtual ODataError ReadError()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a top-level error.
/// </summary>
/// <returns>Task which when completed returns an <see cref="ODataError"/> representing the read error.</returns>
internal virtual Task<ODataError> ReadErrorAsync()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
}
#endif
/// <summary>
/// Read a set of top-level entity reference links.
/// </summary>
/// <returns>An <see cref="ODataEntityReferenceLinks"/> representing the read links.</returns>
internal virtual ODataEntityReferenceLinks ReadEntityReferenceLinks()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLinks);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a set of top-level entity reference links.
/// </summary>
/// <returns>Task which when completed returns an <see cref="ODataEntityReferenceLinks"/> representing the read links.</returns>
internal virtual Task<ODataEntityReferenceLinks> ReadEntityReferenceLinksAsync()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLinks);
}
#endif
/// <summary>
/// Read a top-level entity reference link.
/// </summary>
/// <returns>An <see cref="ODataEntityReferenceLink"/> representing the read entity reference link.</returns>
internal virtual ODataEntityReferenceLink ReadEntityReferenceLink()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLink);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a top-level entity reference link.
/// </summary>
/// <returns>Task which when completed returns an <see cref="ODataEntityReferenceLink"/> representing the read entity reference link.</returns>
internal virtual Task<ODataEntityReferenceLink> ReadEntityReferenceLinkAsync()
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLink);
}
#endif
/// <summary>
/// Read a top-level value.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected type reference for the value to be read; null if no expected type is available.</param>
/// <returns>An <see cref="object"/> representing the read value.</returns>
internal virtual object ReadValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Value);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a top-level value.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected type reference for the value to be read; null if no expected type is available.</param>
/// <returns>Task which when completed returns an <see cref="object"/> representing the read value.</returns>
internal virtual Task<object> ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
DebugUtils.CheckNoExternalCallers();
throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Value);
}
#endif
/// <summary>
/// Check if the object has been disposed.
/// </summary>
/// <exception cref="ObjectDisposedException">If the object has already been disposed.</exception>
internal void VerifyNotDisposed()
{
DebugUtils.CheckNoExternalCallers();
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
/// <summary>
/// Asserts that the input context was created for synchronous operation.
/// </summary>
[Conditional("DEBUG")]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Needs to access this in debug only.")]
internal void AssertSynchronous()
{
DebugUtils.CheckNoExternalCallers();
#if DEBUG
Debug.Assert(this.synchronous, "The method should only be called on a synchronous input context.");
#endif
}
/// <summary>
/// Asserts that the input context was created for asynchronous operation.
/// </summary>
[Conditional("DEBUG")]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Needs to access this in debug only.")]
internal void AssertAsynchronous()
{
DebugUtils.CheckNoExternalCallers();
#if DEBUG
Debug.Assert(!this.synchronous, "The method should only be called on an asynchronous input context.");
#endif
}
/// <summary>
/// Creates a new instance of a duplicate property names checker.
/// </summary>
/// <returns>The newly created instance of duplicate property names checker.</returns>
internal DuplicatePropertyNamesChecker CreateDuplicatePropertyNamesChecker()
{
DebugUtils.CheckNoExternalCallers();
return new DuplicatePropertyNamesChecker(this.MessageReaderSettings.ReaderBehavior.AllowDuplicatePropertyNames, this.ReadingResponse);
}
/// <summary>
/// Disposes the input context.
/// </summary>
protected abstract void DisposeImplementation();
/// <summary>
/// Perform the actual cleanup work.
/// </summary>
/// <param name="disposing">If 'true' this method is called from user code; if 'false' it is called by the runtime.</param>
private void Dispose(bool disposing)
{
this.disposed = true;
if (disposing)
{
this.DisposeImplementation();
}
}
/// <summary>
/// Creates an exception which reports that the specified payload kind if not support by this format.
/// </summary>
/// <param name="payloadKind">The payload kind which is not supported.</param>
/// <returns>An exception to throw.</returns>
private ODataException CreatePayloadKindNotSupportedException(ODataPayloadKind payloadKind)
{
return new ODataException(Strings.ODataInputContext_UnsupportedPayloadKindForFormat(this.format.ToString(), payloadKind.ToString()));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public abstract class Stream : IDisposable
{
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
[Pure]
get;
}
public virtual bool CanTimeout
{
[Pure]
get
{
return false;
}
}
public abstract bool CanWrite
{
[Pure]
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, int bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
ValidateCopyToArguments(destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
Debug.Assert(CanRead);
Debug.Assert(destination.CanWrite);
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
CopyTo(destination, bufferSize);
}
public void CopyTo(Stream destination, int bufferSize)
{
ValidateCopyToArguments(destination, bufferSize);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
return state.Item1.Read(state.Item2, state.Item3, state.Item4); // this.Read(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
state.Item1.Write(state.Item2, state.Item3, state.Item4); // this.Write(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
{
return -1;
}
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
internal void ValidateCopyToArguments(Stream destination, int bufferSize)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
}
if (!CanRead && !CanWrite)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!destination.CanRead && !destination.CanWrite)
{
throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
}
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
if (!destination.CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
}
private sealed class NullStream : Stream
{
internal NullStream() { }
public override bool CanRead
{
[Pure]
get
{ return true; }
}
public override bool CanWrite
{
[Pure]
get
{ return true; }
}
public override bool CanSeek
{
[Pure]
get
{ return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return 0; }
set { }
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments for compat, since previously this
// method was inherited from Stream, which did check its arguments.
ValidateCopyToArguments(destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
#pragma warning disable 1998 // async method with no await
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
#pragma warning disable 1998 // async method with no await
public override async Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
#pragma warning restore 1998
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
#pragma warning disable 1998 // async method with no await
public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
/// Structure specifying parameters of a newly created graphics pipeline.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct GraphicsPipelineCreateInfo
{
/// <summary>
/// A bitmask of PipelineCreateFlagBits controlling how the pipeline
/// will be generated, as described below.
/// </summary>
public SharpVk.PipelineCreateFlags? Flags
{
get;
set;
}
/// <summary>
/// An array of size stageCount structures of type
/// PipelineShaderStageCreateInfo describing the set of the shader
/// stages to be included in the graphics pipeline.
/// </summary>
public SharpVk.PipelineShaderStageCreateInfo[] Stages
{
get;
set;
}
/// <summary>
/// An instance of the PipelineVertexInputStateCreateInfo structure.
/// </summary>
public SharpVk.PipelineVertexInputStateCreateInfo? VertexInputState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineInputAssemblyStateCreateInfo structure
/// which determines input assembly behavior.
/// </summary>
public SharpVk.PipelineInputAssemblyStateCreateInfo? InputAssemblyState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineTessellationStateCreateInfo structure,
/// or Null if the pipeline does not include a tessellation control
/// shader stage and tessellation evaluation shader stage.
/// </summary>
public SharpVk.PipelineTessellationStateCreateInfo? TessellationState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineViewportStateCreateInfo structure, or
/// Null if the pipeline has rasterization disabled.
/// </summary>
public SharpVk.PipelineViewportStateCreateInfo? ViewportState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineRasterizationStateCreateInfo structure.
/// </summary>
public SharpVk.PipelineRasterizationStateCreateInfo RasterizationState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineMultisampleStateCreateInfo, or Null if
/// the pipeline has rasterization disabled.
/// </summary>
public SharpVk.PipelineMultisampleStateCreateInfo? MultisampleState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineDepthStencilStateCreateInfo structure,
/// or Null if the pipeline has rasterization disabled or if the
/// subpass of the render pass the pipeline is created against does not
/// use a depth/stencil attachment.
/// </summary>
public SharpVk.PipelineDepthStencilStateCreateInfo? DepthStencilState
{
get;
set;
}
/// <summary>
/// An instance of the PipelineColorBlendStateCreateInfo structure, or
/// Null if the pipeline has rasterization disabled or if the subpass
/// of the render pass the pipeline is created against does not use any
/// color attachments.
/// </summary>
public SharpVk.PipelineColorBlendStateCreateInfo? ColorBlendState
{
get;
set;
}
/// <summary>
/// A pointer to PipelineDynamicStateCreateInfo and is used to indicate
/// which properties of the pipeline state object are dynamic and can
/// be changed independently of the pipeline state. This can be Null,
/// which means no state in the pipeline is considered dynamic.
/// </summary>
public SharpVk.PipelineDynamicStateCreateInfo? DynamicState
{
get;
set;
}
/// <summary>
/// The description of binding locations used by both the pipeline and
/// descriptor sets used with the pipeline.
/// </summary>
public SharpVk.PipelineLayout Layout
{
get;
set;
}
/// <summary>
/// A handle to a render pass object describing the environment in
/// which the pipeline will be used; the pipeline must only be used
/// with an instance of any render pass compatible with the one
/// provided.
/// </summary>
public SharpVk.RenderPass RenderPass
{
get;
set;
}
/// <summary>
/// The index of the subpass in the render pass where this pipeline
/// will be used.
/// </summary>
public uint Subpass
{
get;
set;
}
/// <summary>
/// A pipeline to derive from.
/// </summary>
public SharpVk.Pipeline BasePipelineHandle
{
get;
set;
}
/// <summary>
/// An index into the pCreateInfos parameter to use as a pipeline to
/// derive from.
/// </summary>
public int BasePipelineIndex
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.GraphicsPipelineCreateInfo* pointer)
{
pointer->SType = StructureType.GraphicsPipelineCreateInfo;
pointer->Next = null;
if (this.Flags != null)
{
pointer->Flags = this.Flags.Value;
}
else
{
pointer->Flags = default(SharpVk.PipelineCreateFlags);
}
pointer->StageCount = (uint)(Interop.HeapUtil.GetLength(this.Stages));
if (this.Stages != null)
{
var fieldPointer = (SharpVk.Interop.PipelineShaderStageCreateInfo*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.PipelineShaderStageCreateInfo>(this.Stages.Length).ToPointer());
for(int index = 0; index < (uint)(this.Stages.Length); index++)
{
this.Stages[index].MarshalTo(&fieldPointer[index]);
}
pointer->Stages = fieldPointer;
}
else
{
pointer->Stages = null;
}
if (this.VertexInputState != null)
{
pointer->VertexInputState = (SharpVk.Interop.PipelineVertexInputStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineVertexInputStateCreateInfo>());
this.VertexInputState.Value.MarshalTo(pointer->VertexInputState);
}
else
{
pointer->VertexInputState = default(SharpVk.Interop.PipelineVertexInputStateCreateInfo*);
}
if (this.InputAssemblyState != null)
{
pointer->InputAssemblyState = (SharpVk.Interop.PipelineInputAssemblyStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineInputAssemblyStateCreateInfo>());
this.InputAssemblyState.Value.MarshalTo(pointer->InputAssemblyState);
}
else
{
pointer->InputAssemblyState = default(SharpVk.Interop.PipelineInputAssemblyStateCreateInfo*);
}
if (this.TessellationState != null)
{
pointer->TessellationState = (SharpVk.Interop.PipelineTessellationStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineTessellationStateCreateInfo>());
this.TessellationState.Value.MarshalTo(pointer->TessellationState);
}
else
{
pointer->TessellationState = default(SharpVk.Interop.PipelineTessellationStateCreateInfo*);
}
if (this.ViewportState != null)
{
pointer->ViewportState = (SharpVk.Interop.PipelineViewportStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineViewportStateCreateInfo>());
this.ViewportState.Value.MarshalTo(pointer->ViewportState);
}
else
{
pointer->ViewportState = default(SharpVk.Interop.PipelineViewportStateCreateInfo*);
}
pointer->RasterizationState = (SharpVk.Interop.PipelineRasterizationStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineRasterizationStateCreateInfo>());
this.RasterizationState.MarshalTo(pointer->RasterizationState);
if (this.MultisampleState != null)
{
pointer->MultisampleState = (SharpVk.Interop.PipelineMultisampleStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineMultisampleStateCreateInfo>());
this.MultisampleState.Value.MarshalTo(pointer->MultisampleState);
}
else
{
pointer->MultisampleState = default(SharpVk.Interop.PipelineMultisampleStateCreateInfo*);
}
if (this.DepthStencilState != null)
{
pointer->DepthStencilState = (SharpVk.Interop.PipelineDepthStencilStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineDepthStencilStateCreateInfo>());
this.DepthStencilState.Value.MarshalTo(pointer->DepthStencilState);
}
else
{
pointer->DepthStencilState = default(SharpVk.Interop.PipelineDepthStencilStateCreateInfo*);
}
if (this.ColorBlendState != null)
{
pointer->ColorBlendState = (SharpVk.Interop.PipelineColorBlendStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineColorBlendStateCreateInfo>());
this.ColorBlendState.Value.MarshalTo(pointer->ColorBlendState);
}
else
{
pointer->ColorBlendState = default(SharpVk.Interop.PipelineColorBlendStateCreateInfo*);
}
if (this.DynamicState != null)
{
pointer->DynamicState = (SharpVk.Interop.PipelineDynamicStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineDynamicStateCreateInfo>());
this.DynamicState.Value.MarshalTo(pointer->DynamicState);
}
else
{
pointer->DynamicState = default(SharpVk.Interop.PipelineDynamicStateCreateInfo*);
}
pointer->Layout = this.Layout?.handle ?? default(SharpVk.Interop.PipelineLayout);
pointer->RenderPass = this.RenderPass?.handle ?? default(SharpVk.Interop.RenderPass);
pointer->Subpass = this.Subpass;
pointer->BasePipelineHandle = this.BasePipelineHandle?.handle ?? default(SharpVk.Interop.Pipeline);
pointer->BasePipelineIndex = this.BasePipelineIndex;
}
}
}
| |
#region License
/*
* WebSocketServiceHostManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2013 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Manages the WebSocket services provided by the <see cref="HttpServer"/> and
/// <see cref="WebSocketServer"/>.
/// </summary>
public class WebSocketServiceHostManager
{
#region Private Fields
private volatile bool _keepClean;
private Logger _logger;
private Dictionary<string, IWebSocketServiceHost> _serviceHosts;
private object _sync;
#endregion
#region Internal Constructors
internal WebSocketServiceHostManager ()
: this (new Logger ())
{
}
internal WebSocketServiceHostManager (Logger logger)
{
_logger = logger;
_keepClean = true;
_serviceHosts = new Dictionary<string, IWebSocketServiceHost> ();
_sync = new object ();
}
#endregion
#region Internal Properties
internal bool KeepClean {
get {
return _keepClean;
}
set {
lock (_sync)
{
if (_keepClean ^ value)
{
_keepClean = value;
foreach (var host in _serviceHosts.Values)
host.KeepClean = value;
}
}
}
}
internal IEnumerable<IWebSocketServiceHost> ServiceHosts {
get {
lock (_sync)
{
return _serviceHosts.Values.ToList ();
}
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the connection count to the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// An <see cref="int"/> that contains the connection count to the WebSocket services.
/// </value>
public int ConnectionCount {
get {
var count = 0;
foreach (var host in ServiceHosts)
count += host.ConnectionCount;
return count;
}
}
/// <summary>
/// Gets the number of the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// An <see cref="int"/> that contains the number of the WebSocket services.
/// </value>
public int Count {
get {
lock (_sync)
{
return _serviceHosts.Count;
}
}
}
/// <summary>
/// Gets the collection of every path to the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// An IEnumerable<string> that contains the collection of every path to the WebSocket services.
/// </value>
public IEnumerable<string> ServicePaths {
get {
lock (_sync)
{
return _serviceHosts.Keys.ToList ();
}
}
}
#endregion
#region Private Methods
private Dictionary<string, Dictionary<string, bool>> broadping (byte [] data)
{
var result = new Dictionary<string, Dictionary<string, bool>> ();
foreach (var service in copy ())
result.Add (service.Key, service.Value.Sessions.BroadpingInternally (data));
return result;
}
private Dictionary<string, IWebSocketServiceHost> copy ()
{
lock (_sync)
{
return new Dictionary<string, IWebSocketServiceHost> (_serviceHosts);
}
}
#endregion
#region Internal Methods
internal void Add (string servicePath, IWebSocketServiceHost serviceHost)
{
servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash ();
lock (_sync)
{
IWebSocketServiceHost host;
if (_serviceHosts.TryGetValue (servicePath, out host))
{
_logger.Error (
"The WebSocket service with the specified path already exists.\npath: " + servicePath);
return;
}
_serviceHosts.Add (servicePath, serviceHost);
}
}
internal bool Remove (string servicePath)
{
servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash ();
IWebSocketServiceHost host;
lock (_sync)
{
if (!_serviceHosts.TryGetValue (servicePath, out host))
{
_logger.Error (
"The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
_serviceHosts.Remove (servicePath);
}
host.Sessions.Stop (((ushort) CloseStatusCode.AWAY).ToByteArray (ByteOrder.BIG));
return true;
}
internal void Stop ()
{
lock (_sync)
{
foreach (var host in _serviceHosts.Values)
host.Sessions.Stop ();
_serviceHosts.Clear ();
}
}
internal void Stop (byte [] data)
{
lock (_sync)
{
foreach (var host in _serviceHosts.Values)
host.Sessions.Stop (data);
_serviceHosts.Clear ();
}
}
internal bool TryGetServiceHost (string servicePath, out IWebSocketServiceHost serviceHost)
{
servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash ();
lock (_sync)
{
return _serviceHosts.TryGetValue (servicePath, out serviceHost);
}
}
#endregion
#region Public Methods
/// <summary>
/// Broadcasts the specified array of <see cref="byte"/> to all clients of the WebSocket services
/// provided by the WebSocket server.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> to broadcast.
/// </param>
public void Broadcast (byte [] data)
{
var msg = data.CheckIfValidSendData ();
if (msg != null)
{
_logger.Error (msg);
return;
}
foreach (var host in ServiceHosts)
host.Sessions.BroadcastInternally (data);
}
/// <summary>
/// Broadcasts the specified <see cref="string"/> to all clients of the WebSocket services
/// provided by the WebSocket server.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> to broadcast.
/// </param>
public void Broadcast (string data)
{
var msg = data.CheckIfValidSendData ();
if (msg != null)
{
_logger.Error (msg);
return;
}
foreach (var host in ServiceHosts)
host.Sessions.BroadcastInternally (data);
}
/// <summary>
/// Broadcasts the specified array of <see cref="byte"/> to all clients of the WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="data"/> is broadcasted; otherwise, <c>false</c>.
/// </returns>
/// <param name="data">
/// An array of <see cref="byte"/> to broadcast.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool BroadcastTo (byte [] data, string servicePath)
{
var msg = data.CheckIfValidSendData () ?? servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
host.Sessions.BroadcastInternally (data);
return true;
}
/// <summary>
/// Broadcasts the specified <see cref="string"/> to all clients of the WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="data"/> is broadcasted; otherwise, <c>false</c>.
/// </returns>
/// <param name="data">
/// A <see cref="string"/> to broadcast.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool BroadcastTo (string data, string servicePath)
{
var msg = data.CheckIfValidSendData () ?? servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
host.Sessions.BroadcastInternally (data);
return true;
}
/// <summary>
/// Sends Pings to all clients of the WebSocket services provided by the WebSocket server.
/// </summary>
/// <returns>
/// A Dictionary<string, Dictionary<string, bool>> that contains the collection of
/// service paths and pairs of session ID and value indicating whether each WebSocket service
/// received a Pong from each client in a time.
/// </returns>
public Dictionary<string, Dictionary<string, bool>> Broadping ()
{
return broadping (new byte [] {});
}
/// <summary>
/// Sends Pings with the specified <paramref name="message"/> to all clients of the WebSocket services
/// provided by the WebSocket server.
/// </summary>
/// <returns>
/// A Dictionary<string, Dictionary<string, bool>> that contains the collection of
/// service paths and pairs of session ID and value indicating whether each WebSocket service
/// received a Pong from each client in a time.
/// If <paramref name="message"/> is invalid, returns <see langword="null"/>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
public Dictionary<string, Dictionary<string, bool>> Broadping (string message)
{
if (message == null || message.Length == 0)
return broadping (new byte [] {});
var data = Encoding.UTF8.GetBytes (message);
var msg = data.CheckIfValidPingData ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
return broadping (data);
}
/// <summary>
/// Sends Pings to all clients of the WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// A Dictionary<string, bool> that contains the collection of pairs of session ID and value
/// indicating whether the WebSocket service received a Pong from each client in a time.
/// If the WebSocket service is not found, returns <see langword="null"/>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public Dictionary<string, bool> BroadpingTo (string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return null;
}
return host.Sessions.BroadpingInternally (new byte [] {});
}
/// <summary>
/// Sends Pings with the specified <paramref name="message"/> to all clients of the WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// A Dictionary<string, bool> that contains the collection of pairs of session ID and value
/// indicating whether the WebSocket service received a Pong from each client in a time.
/// If the WebSocket service is not found, returns <see langword="null"/>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public Dictionary<string, bool> BroadpingTo (string message, string servicePath)
{
if (message == null || message.Length == 0)
return BroadpingTo (servicePath);
var data = Encoding.UTF8.GetBytes (message);
var msg = data.CheckIfValidPingData () ?? servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return null;
}
return host.Sessions.BroadpingInternally (data);
}
/// <summary>
/// Closes the session with the specified <paramref name="id"/> and
/// <paramref name="servicePath"/>.
/// </summary>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public void CloseSession (string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return;
}
host.Sessions.CloseSession (id);
}
/// <summary>
/// Closes the session with the specified <paramref name="code"/>, <paramref name="reason"/>,
/// <paramref name="id"/> and <paramref name="servicePath"/>.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that contains a status code indicating the reason for closure.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for closure.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public void CloseSession (ushort code, string reason, string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return;
}
host.Sessions.CloseSession (code, reason, id);
}
/// <summary>
/// Closes the session with the specified <paramref name="code"/>, <paramref name="reason"/>,
/// <paramref name="id"/> and <paramref name="servicePath"/>.
/// </summary>
/// <param name="code">
/// A <see cref="CloseStatusCode"/> that contains a status code indicating the reason for closure.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for closure.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public void CloseSession (CloseStatusCode code, string reason, string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return;
}
host.Sessions.CloseSession (code, reason, id);
}
/// <summary>
/// Gets the connection count to the WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// An <see cref="int"/> that contains the connection count if the WebSocket service is successfully
/// found; otherwise, <c>-1</c>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public int GetConnectionCount (string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return -1;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return -1;
}
return host.ConnectionCount;
}
/// <summary>
/// Gets the manager of the sessions to the WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// A <see cref="WebSocketSessionManager"/> if the WebSocket service is successfully found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public WebSocketSessionManager GetSessions (string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return null;
}
return host.Sessions;
}
/// <summary>
/// Sends a Ping to the client associated with the specified <paramref name="id"/> and
/// <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the WebSocket service with <paramref name="servicePath"/> receives a Pong
/// from the client in a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination for the Ping.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool PingTo (string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
return host.Sessions.PingTo (id);
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to the client associated with
/// the specified <paramref name="id"/> and <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the WebSocket service with <paramref name="servicePath"/> receives a Pong
/// from the client in a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination for the Ping.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool PingTo (string message, string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
return host.Sessions.PingTo (message, id);
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client associated with the specified
/// <paramref name="id"/> and <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="data"/> is successfully sent; otherwise, <c>false</c>.
/// </returns>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination for the data.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool SendTo (byte [] data, string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
return host.Sessions.SendTo (data, id);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client associated with the specified
/// <paramref name="id"/> and <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="data"/> is successfully sent; otherwise, <c>false</c>.
/// </returns>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination for the data.
/// </param>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public bool SendTo (string data, string id, string servicePath)
{
var msg = servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
return false;
}
IWebSocketServiceHost host;
if (!TryGetServiceHost (servicePath, out host))
{
_logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
return host.Sessions.SendTo (data, id);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace who_is_that_guy.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Abp.Extensions;
using Abp.Runtime.Session;
namespace Abp.Domain.Uow
{
/// <summary>
/// Base for all Unit Of Work classes.
/// </summary>
public abstract class UnitOfWorkBase : IUnitOfWork
{
public string Id { get; private set; }
public IUnitOfWork Outer { get; set; }
/// <inheritdoc/>
public event EventHandler Completed;
/// <inheritdoc/>
public event EventHandler<UnitOfWorkFailedEventArgs> Failed;
/// <inheritdoc/>
public event EventHandler Disposed;
/// <inheritdoc/>
public UnitOfWorkOptions Options { get; private set; }
/// <inheritdoc/>
public IReadOnlyList<DataFilterConfiguration> Filters
{
get { return _filters.ToImmutableList(); }
}
private readonly List<DataFilterConfiguration> _filters;
/// <summary>
/// Gets default UOW options.
/// </summary>
protected IUnitOfWorkDefaultOptions DefaultOptions { get; private set; }
/// <summary>
/// Gets the connection string resolver.
/// </summary>
protected IConnectionStringResolver ConnectionStringResolver { get; private set; }
/// <summary>
/// Gets a value indicates that this unit of work is disposed or not.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Reference to current ABP session.
/// </summary>
public IAbpSession AbpSession { private get; set; }
/// <summary>
/// Is <see cref="Begin"/> method called before?
/// </summary>
private bool _isBeginCalledBefore;
/// <summary>
/// Is <see cref="Complete"/> method called before?
/// </summary>
private bool _isCompleteCalledBefore;
/// <summary>
/// Is this unit of work successfully completed.
/// </summary>
private bool _succeed;
/// <summary>
/// A reference to the exception if this unit of work failed.
/// </summary>
private Exception _exception;
private int? _tenantId;
/// <summary>
/// Constructor.
/// </summary>
protected UnitOfWorkBase(IConnectionStringResolver connectionStringResolver, IUnitOfWorkDefaultOptions defaultOptions)
{
DefaultOptions = defaultOptions;
ConnectionStringResolver = connectionStringResolver;
Id = Guid.NewGuid().ToString("N");
_filters = defaultOptions.Filters.ToList();
AbpSession = NullAbpSession.Instance;
}
/// <inheritdoc/>
public void Begin(UnitOfWorkOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
PreventMultipleBegin();
Options = options; //TODO: Do not set options like that, instead make a copy?
SetFilters(options.FilterOverrides);
SetTenantId(AbpSession.TenantId);
BeginUow();
}
/// <inheritdoc/>
public abstract void SaveChanges();
/// <inheritdoc/>
public abstract Task SaveChangesAsync();
/// <inheritdoc/>
public IDisposable DisableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var disabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (_filters[filterIndex].IsEnabled)
{
disabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], false);
}
}
disabledFilters.ForEach(ApplyDisableFilter);
return new DisposeAction(() => EnableFilter(disabledFilters.ToArray()));
}
/// <inheritdoc/>
public IDisposable EnableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var enabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (!_filters[filterIndex].IsEnabled)
{
enabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], true);
}
}
enabledFilters.ForEach(ApplyEnableFilter);
return new DisposeAction(() => DisableFilter(enabledFilters.ToArray()));
}
/// <inheritdoc/>
public bool IsFilterEnabled(string filterName)
{
return GetFilter(filterName).IsEnabled;
}
/// <inheritdoc/>
public IDisposable SetFilterParameter(string filterName, string parameterName, object value)
{
var filterIndex = GetFilterIndex(filterName);
var newfilter = new DataFilterConfiguration(_filters[filterIndex]);
//Store old value
object oldValue = null;
var hasOldValue = newfilter.FilterParameters.ContainsKey(parameterName);
if (hasOldValue)
{
oldValue = newfilter.FilterParameters[parameterName];
}
newfilter.FilterParameters[parameterName] = value;
_filters[filterIndex] = newfilter;
ApplyFilterParameterValue(filterName, parameterName, value);
return new DisposeAction(() =>
{
//Restore old value
if (hasOldValue)
{
SetFilterParameter(filterName, parameterName, oldValue);
}
});
}
public IDisposable SetTenantId(int? tenantId)
{
var oldTenantId = _tenantId;
_tenantId = tenantId;
var mustHaveTenantEnableChange = tenantId == null
? DisableFilter(AbpDataFilters.MustHaveTenant)
: EnableFilter(AbpDataFilters.MustHaveTenant);
var mayHaveTenantChange = SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId);
var mustHaveTenantChange = SetFilterParameter(AbpDataFilters.MustHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId ?? 0);
return new DisposeAction(() =>
{
mayHaveTenantChange.Dispose();
mustHaveTenantChange.Dispose();
mustHaveTenantEnableChange.Dispose();
_tenantId = oldTenantId;
});
}
public int? GetTenantId()
{
return _tenantId;
}
/// <inheritdoc/>
public void Complete()
{
PreventMultipleComplete();
try
{
CompleteUow();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public async Task CompleteAsync()
{
PreventMultipleComplete();
try
{
await CompleteUowAsync();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
if (!_succeed)
{
OnFailed(_exception);
}
DisposeUow();
OnDisposed();
}
/// <summary>
/// Should be implemented by derived classes to start UOW.
/// </summary>
protected abstract void BeginUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract void CompleteUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract Task CompleteUowAsync();
/// <summary>
/// Should be implemented by derived classes to dispose UOW.
/// </summary>
protected abstract void DisposeUow();
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to disable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyDisableFilter(string filterName)
{
//throw new NotImplementedException("DisableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to enable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyEnableFilter(string filterName)
{
//throw new NotImplementedException("EnableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to set a parameter's value.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value)
{
//throw new NotImplementedException("SetFilterParameterValue is not implemented for " + GetType().FullName);
}
protected virtual string ResolveConnectionString(ConnectionStringResolveArgs args)
{
return ConnectionStringResolver.GetNameOrConnectionString(args);
}
/// <summary>
/// Called to trigger <see cref="Completed"/> event.
/// </summary>
protected virtual void OnCompleted()
{
Completed.InvokeSafely(this);
}
/// <summary>
/// Called to trigger <see cref="Failed"/> event.
/// </summary>
/// <param name="exception">Exception that cause failure</param>
protected virtual void OnFailed(Exception exception)
{
Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception));
}
/// <summary>
/// Called to trigger <see cref="Disposed"/> event.
/// </summary>
protected virtual void OnDisposed()
{
Disposed.InvokeSafely(this);
}
private void PreventMultipleBegin()
{
if (_isBeginCalledBefore)
{
throw new AbpException("This unit of work has started before. Can not call Start method more than once.");
}
_isBeginCalledBefore = true;
}
private void PreventMultipleComplete()
{
if (_isCompleteCalledBefore)
{
throw new AbpException("Complete is called before!");
}
_isCompleteCalledBefore = true;
}
private void SetFilters(List<DataFilterConfiguration> filterOverrides)
{
for (var i = 0; i < _filters.Count; i++)
{
var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName);
if (filterOverride != null)
{
_filters[i] = filterOverride;
}
}
if (AbpSession.TenantId == null)
{
ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false);
}
}
private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled)
{
if (filterOverrides.Any(f => f.FilterName == filterName))
{
return;
}
var index = _filters.FindIndex(f => f.FilterName == filterName);
if (index < 0)
{
return;
}
if (_filters[index].IsEnabled == isEnabled)
{
return;
}
_filters[index] = new DataFilterConfiguration(filterName, isEnabled);
}
private DataFilterConfiguration GetFilter(string filterName)
{
var filter = _filters.FirstOrDefault(f => f.FilterName == filterName);
if (filter == null)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filter;
}
private int GetFilterIndex(string filterName)
{
var filterIndex = _filters.FindIndex(f => f.FilterName == filterName);
if (filterIndex < 0)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filterIndex;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
namespace Microsoft.Azure.Management.Resources
{
public partial class FeatureClient : ServiceClient<FeatureClient>, IFeatureClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IFeatures _features;
/// <summary>
/// Operations for managing preview features.
/// </summary>
public virtual IFeatures Features
{
get { return this._features; }
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
public FeatureClient()
: base()
{
this._features = new Features(this);
this._apiVersion = "2015-12-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public FeatureClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public FeatureClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public FeatureClient(HttpClient httpClient)
: base(httpClient)
{
this._features = new Features(this);
this._apiVersion = "2015-12-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public FeatureClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the FeatureClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public FeatureClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another FeatureClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of FeatureClient to clone to
/// </param>
protected override void Clone(ServiceClient<FeatureClient> client)
{
base.Clone(client);
if (client is FeatureClient)
{
FeatureClient clonedClient = ((FeatureClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 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.Batch.Protocol
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// A client for issuing REST requests to the Azure Batch service.
/// </summary>
public partial class BatchServiceClient : Microsoft.Rest.ServiceClient<BatchServiceClient>, IBatchServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client API Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationOperations.
/// </summary>
public virtual IApplicationOperations Application { get; private set; }
/// <summary>
/// Gets the IPoolOperations.
/// </summary>
public virtual IPoolOperations Pool { get; private set; }
/// <summary>
/// Gets the IAccountOperations.
/// </summary>
public virtual IAccountOperations Account { get; private set; }
/// <summary>
/// Gets the IJobOperations.
/// </summary>
public virtual IJobOperations Job { get; private set; }
/// <summary>
/// Gets the ICertificateOperations.
/// </summary>
public virtual ICertificateOperations Certificate { get; private set; }
/// <summary>
/// Gets the IFileOperations.
/// </summary>
public virtual IFileOperations File { get; private set; }
/// <summary>
/// Gets the IJobScheduleOperations.
/// </summary>
public virtual IJobScheduleOperations JobSchedule { get; private set; }
/// <summary>
/// Gets the ITaskOperations.
/// </summary>
public virtual ITaskOperations Task { get; private set; }
/// <summary>
/// Gets the IComputeNodeOperations.
/// </summary>
public virtual IComputeNodeOperations ComputeNode { get; private set; }
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BatchServiceClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BatchServiceClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BatchServiceClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BatchServiceClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Application = new ApplicationOperations(this);
this.Pool = new PoolOperations(this);
this.Account = new AccountOperations(this);
this.Job = new JobOperations(this);
this.Certificate = new CertificateOperations(this);
this.File = new FileOperations(this);
this.JobSchedule = new JobScheduleOperations(this);
this.Task = new TaskOperations(this);
this.ComputeNode = new ComputeNodeOperations(this);
this.BaseUri = new System.Uri("https://batch.core.windows.net");
this.ApiVersion = "2017-01-01.4.0";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using UnityEngine;
using System.Collections;
//REV: I HAVE DONE THE WORK UPTO VIDEO S03_019 29/11/30
public class TP_Camera : MonoBehaviour
{
public static TP_Camera Instance;
public Transform TargetLookAt ;
public float Distance = 5.0f;
public float DistanceMin = 3.0f;
public float DistanceMax = 10.0f;
public float DistanceSmooth = 0.05f;
public float DistanceResumeSmooth =1f;
public float X_MouseSensitivity = 5f;
public float Y_MouseSensitivity = 5f;
public float MouseWheelSensitivity = 5f;
public float X_Smooth = 0.05f;
public float Y_Smooth = 0.1f;
public float Y_MinLimit = -40f;
public float Y_MaxLimit = 80f;
public float OcclusionDistanceStep = 0.5f;
public int MaxOcclusionChecks = 10;
private float mouseX = 0f;
private float mouseY = 0f;
private float velX = 0;
private float velY = 0;
private float velZ = 0;
private float velDistance = 0f;
private float startDistance = 0f;
private Vector3 position = Vector3.zero;
private Vector3 desiredPosition = Vector3.zero;
private float desiredDistance = 0f;
private float distanceSmooth =0f;
private float preOccludedDistance=0f;
void Awake ()
{
Instance = this;
}
void Start ()
{
Distance = Mathf.Clamp (Distance, DistanceMin, DistanceMax);
startDistance = Distance;
Reset ();
}
void LateUpdate ()
{
if (TargetLookAt == null)
return;
HandlePlayerInput ();
var count = 0;
do
{
CalculateDesiredPosition();
count ++;
} while (CheckIfOccluded(count));
// CheckCameraPoints (TargetLookAt.position, desiredPosition); not wanted eventually
UpdatePosition ();
}
void HandlePlayerInput ()
{
var deadZone = 0.001f;
//RMB right mouse button
if (Input.GetMouseButton (1)) {
//The RMB is down, get mouse axis input
mouseX += Input.GetAxis ("Mouse X") * X_MouseSensitivity;
mouseY -= Input.GetAxis ("Mouse Y") * Y_MouseSensitivity;
// note the inversion by subtraction -=
}
// This is where we limit mouseY rotation
mouseY = Helper.ClampAngle (mouseY, Y_MinLimit, Y_MaxLimit);
if (Input.GetAxis ("Mouse ScrollWheel") < -deadZone || Input.GetAxis ("Mouse ScrollWheel") > deadZone) {
desiredDistance = Mathf.Clamp (Distance - Input.GetAxis ("Mouse ScrollWheel") * MouseWheelSensitivity, DistanceMin, DistanceMax);
preOccludedDistance = Distance;
distanceSmooth = DistanceSmooth;
}
// float t = 0f;
// t = Input.GetAxis ("Mouse ScrollWheel");
//Debug.Log ("Mouse ScrollWheel= " + t);
}
void CalculateDesiredPosition ()
{
//Evaluate Distance
ResetDesiredDistance();
Distance = Mathf.SmoothDamp (Distance, desiredDistance, ref velDistance, distanceSmooth);
//Calculate desired position
desiredPosition = CalculatePosition (mouseY, mouseX, Distance);
//note reversals
}
Vector3 CalculatePosition (float rotationX, float rotationY, float distance)
{
Vector3 direction = new Vector3 (0, 0, -distance);
//-ve distance points behind camera
Quaternion rotation = Quaternion.Euler (rotationX, rotationY, 0);
return TargetLookAt.position + (rotation * direction);
}
bool CheckIfOccluded (int count)
{
var isOccluded = false;
var nearestDistance = CheckCameraPoints (TargetLookAt.position, desiredPosition);
if (nearestDistance != -1) {
if (count < MaxOcclusionChecks)
{
isOccluded = true;
Distance -= OcclusionDistanceStep;
if (Distance < 0.8f)//.25 ORI test for shudder
Distance = 0.8f;//.25 ORI
}
else
Distance = nearestDistance - Camera.main.nearClipPlane;
desiredDistance = Distance;
distanceSmooth = DistanceResumeSmooth;
}
return isOccluded;
}
float CheckCameraPoints (Vector3 fromm, Vector3 to)
{
var nearestDistance = -1f;
RaycastHit hitInfo;
Helper.ClipPlanePoints clipPlanePoints = Helper.ClipPlaneAtNear (to);
// Draw lines in the editor to make it easier to visual
Debug.DrawLine (fromm, to + transform.forward * -GetComponent<Camera>().nearClipPlane, Color.red);
//centreline
Debug.DrawLine (fromm, clipPlanePoints.UpperLeft);
Debug.DrawLine (fromm, clipPlanePoints.LowerLeft);
Debug.DrawLine (fromm, clipPlanePoints.UpperRight);
Debug.DrawLine (fromm, clipPlanePoints.LowerRight);
//box it in
Debug.DrawLine (clipPlanePoints.LowerLeft, clipPlanePoints.UpperLeft);
Debug.DrawLine (clipPlanePoints.UpperLeft, clipPlanePoints.UpperRight);
Debug.DrawLine (clipPlanePoints.UpperRight, clipPlanePoints.LowerRight);
Debug.DrawLine (clipPlanePoints.LowerRight, clipPlanePoints.LowerLeft);
//
if (Physics.Linecast (fromm, clipPlanePoints.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player")
nearestDistance = hitInfo.distance;
//
if (Physics.Linecast (fromm, clipPlanePoints.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, clipPlanePoints.LowerLeft, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
//
if (Physics.Linecast (fromm, clipPlanePoints.LowerRight, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, clipPlanePoints.UpperRight, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, to + transform.forward * -GetComponent<Camera>().nearClipPlane, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
return nearestDistance;
}
void ResetDesiredDistance()
{
if(desiredDistance < preOccludedDistance)
{
var pos= CalculatePosition(mouseY,mouseX,preOccludedDistance);
var nearestDistance = CheckCameraPoints(TargetLookAt.position,pos);
if(nearestDistance == -1 || nearestDistance > preOccludedDistance)
{
desiredDistance =preOccludedDistance;
}
}
}
void UpdatePosition ()
{
var posX = Mathf.SmoothDamp (position.x, desiredPosition.x, ref velX, X_Smooth);
var posY = Mathf.SmoothDamp (position.y, desiredPosition.y, ref velY, Y_Smooth);
var posZ = Mathf.SmoothDamp (position.z, desiredPosition.z, ref velZ, X_Smooth);
//X_Smooth is correct
position = new Vector3 (posX, posY, posZ);
transform.position = position;
transform.LookAt (TargetLookAt);
}
public void Reset ()
{
mouseX = 0;
mouseY = 10;
Distance = startDistance;
desiredDistance = Distance;
preOccludedDistance =Distance;
}
public static void UseExistingOrCreateMainCamera ()
{
GameObject tempCamera;
GameObject targetLookAt;
TP_Camera myCamera;
if (Camera.main != null) {
tempCamera = Camera.main.gameObject;
} else {
tempCamera = new GameObject ("Main Camera");
tempCamera.AddComponent <Camera>();
tempCamera.tag = "MainCamera";
tempCamera.AddComponent <TP_Camera>();
}
myCamera = tempCamera.GetComponent ("TP_Camera") as TP_Camera;
targetLookAt = GameObject.Find ("targetLookAt") as GameObject;
if (targetLookAt == null) {
targetLookAt = new GameObject ("targetLookAt");
targetLookAt.transform.position = Vector3.zero;
}
myCamera.TargetLookAt = targetLookAt.transform;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;
using System.Web.Hosting;
using ImpromptuInterface;
using Timer = System.Threading.Timer;
namespace linger
{
/// <summary>
/// A task worker that watches a job queue and performs work. Jobs are scheduled by priority.
/// </summary>
public class LingerWorker : IRegisteredObject
{
private static readonly IDictionary<Type, IList<string>> Cache = new ConcurrentDictionary<Type, IList<string>>();
private readonly ConcurrentDictionary<int, TaskScheduler> _schedulers;
private readonly ConcurrentDictionary<TaskScheduler, TaskFactory> _factories;
private readonly ConcurrentDictionary<Perform, IList<string>> _pending;
private QueuedTaskScheduler _queue;
private CancellationTokenSource _cancel;
private readonly int _threads;
private static IDisposable _background;
public LingerWorker(int threads)
{
_threads = threads;
_schedulers = new ConcurrentDictionary<int, TaskScheduler>();
_factories = new ConcurrentDictionary<TaskScheduler, TaskFactory>();
_pending = new ConcurrentDictionary<Perform, IList<string>>();
_cancel = new CancellationTokenSource();
}
public void Start()
{
if(_queue == null)
{
_queue = new QueuedTaskScheduler(_threads);
}
// This probaby uses a worker pool thread, so should be replaced eventually
_background = new Timer(state => SeedJobsFromQueue(), null, 0, Linger.SleepDelay * 1000);
}
public void Stop(bool immediate)
{
foreach (var entry in _pending.Where(entry => entry.Value.Contains("Halt")))
{
entry.Key.ActLike<Halt>().Halt(immediate);
}
if (immediate)
{
Stop();
}
}
public void Stop()
{
if(_queue != null)
{
_queue.Dispose();
_queue = null;
}
if(_background != null)
{
_background.Dispose();
_background = null;
}
}
private void SeedJobsFromQueue()
{
var jobs = Linger.Backend.GetNextAvailable(Linger.ReadAhead);
var pending = new Dictionary<Task, CancellationTokenSource>();
foreach(var job in jobs)
{
var scheduler = AcquireScheduler(job);
var scheduled = job;
var cancel = new CancellationTokenSource();
var performer = _factories[scheduler].StartNew(() =>
{
AttemptJob(scheduled);
}, cancel.Token);
pending.Add(performer, cancel);
}
// This is effectively giving all tasks below the current as much time as the current...
foreach(var performer in pending)
{
if (!Task.WaitAll(new[] { performer.Key }, Linger.MaximumRuntime))
{
performer.Value.Cancel();
}
}
}
internal bool AttemptJob(ScheduledJob job, bool persist = true)
{
if(_cancel.IsCancellationRequested)
{
return false;
}
var success = AttemptCycle(job);
if(persist)
{
SaveJobChanges(job, success);
}
_cancel.Token.ThrowIfCancellationRequested();
return success;
}
private bool AttemptCycle(ScheduledJob job)
{
job.Attempts++;
var success = Perform(job);
if (!success)
{
var dueTime = DateTime.Now + Linger.IntervalFunction(job.Attempts);
job.RunAt = dueTime;
}
return success;
}
private static void SaveJobChanges(ScheduledJob job, bool success)
{
if (!success)
{
if(JobWillFail(job))
{
if (Linger.DeleteFailedJobs)
{
Linger.Backend.Delete(job);
return;
}
job.FailedAt = DateTime.Now;
}
}
else
{
if(Linger.DeleteSuccessfulJobs)
{
Linger.Backend.Delete(job);
return;
}
job.SucceededAt = DateTime.Now;
}
job.LockedAt = null;
job.LockedBy = null;
Linger.Backend.Save(job);
// Spawn a new scheduled job using the repeat data
if (success && job.RepeatInfo != null && job.RepeatInfo.NextOccurrence.HasValue)
{
job.Id = 0;
job.RunAt = job.RepeatInfo.NextOccurrence;
job.RepeatInfo.Start = job.RunAt;
Linger.Backend.Save(job, job.RepeatInfo);
}
}
private static bool JobWillFail(ScheduledJob job)
{
return job.Attempts >= Linger.MaximumAttempts;
}
private bool Perform(ScheduledJob job)
{
var success = false;
Perform handler = null;
IList<string> methods = null;
try
{
// Acquire the handler
handler = HandlerSerializer.Deserialize<object>(job.Handler).ActLike<Perform>();
if (handler == null)
{
job.LastError = "Missing handler";
return false;
}
// Acquire and cache method manifest
var handlerType = handler.GetType();
if (!Cache.TryGetValue(handlerType, out methods))
{
methods = handlerType.GetMethods().Select(m => m.Name).ToList();
Cache.Add(handlerType, methods);
}
_pending.TryAdd(handler, methods);
// Before
if(methods.Contains("Before"))
{
handler.ActLike<Before>().Before();
}
// Perform
success = handler.Perform();
if(success)
{
if (methods.Contains("Success"))
{
handler.ActLike<Success>().Success();
}
}
// Failure
if(JobWillFail(job) && methods.Contains("Failure"))
{
{
handler.ActLike<Failure>().Failure();
}
}
// After
if(methods.Contains("After"))
{
handler.ActLike<After>().After();
}
_pending.TryRemove(handler, out methods);
}
catch (OperationCanceledException)
{
job.LastError = "Cancelled";
}
catch (Exception ex)
{
job.LastError = ex.Message;
if (methods != null && methods.Contains("Error"))
{
handler.ActLike<Error>().Error(ex);
}
}
return success;
}
private TaskScheduler AcquireScheduler(ScheduledJob job)
{
TaskScheduler scheduler;
if (!_schedulers.TryGetValue(job.Priority, out scheduler))
{
scheduler = _queue.ActivateNewQueue(job.Priority);
var factory = new TaskFactory(
_cancel.Token, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, scheduler
);
_schedulers.TryAdd(job.Priority, scheduler);
_factories.TryAdd(scheduler, factory);
}
return scheduler;
}
public void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if(_cancel != null)
{
_cancel.Cancel();
_cancel.Token.WaitHandle.WaitOne();
_cancel.Dispose();
_cancel = null;
}
_factories.Clear();
_schedulers.Clear();
if (_queue == null)
{
return;
}
_queue.Dispose();
_queue = null;
}
}
}
| |
using System;
using System.Reflection;
using System.Text;
using log4net;
using PacketDotNet.MiscUtil.Conversion;
using PacketDotNet.Utils;
namespace PacketDotNet.LLDP
{
/// <summary>
/// A Time to Live TLV
/// [TLV Type Length : 2][Mgmt Addr length : 1][Mgmt Addr Subtype : 1][Mgmt Addr : 1-31]
/// [Interface Subtype : 1][Interface number : 4][OID length : 1][OID : 0-128]
/// </summary>
public class ManagementAddress : TLV
{
#if DEBUG
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#else
// NOTE: No need to warn about lack of use, the compiler won't
// put any calls to 'log' here but we need 'log' to exist to compile
#pragma warning disable 0169, 0649
private static readonly ILogInactive log;
#pragma warning restore 0169, 0649
#endif
/// <summary>
/// Number of bytes in the AddressLength field
/// </summary>
private const int MgmtAddressLengthLength = 1;
/// <summary>
/// Number of bytes in the interface number subtype field
/// </summary>
private const int InterfaceNumberSubTypeLength = 1;
/// <summary>
/// Number of bytes in the interface number field
/// </summary>
private const int InterfaceNumberLength = 4;
/// <summary>
/// Number of bytes in the object identifier length field
/// </summary>
private const int ObjectIdentifierLengthLength = 1;
/// <summary>
/// Maximum number of bytes in the object identifier field
/// </summary>
private const int maxObjectIdentifierLength = 128;
#region Constructors
/// <summary>
/// Creates a Management Address TLV
/// </summary>
/// <param name="bytes">
/// The LLDP Data unit being modified
/// </param>
/// <param name="offset">
/// The Management Address TLV's offset from the
/// origin of the LLDP
/// </param>
public ManagementAddress(byte[] bytes, int offset) : base(bytes, offset)
{
log.Debug("");
}
/// <summary>
/// Creates a Management Address TLV and sets it value
/// </summary>
/// <param name="managementAddress">
/// The Management Address
/// </param>
/// <param name="interfaceSubType">
/// The Interface Numbering Sub Type
/// </param>
/// <param name="ifNumber">
/// The Interface Number
/// </param>
/// <param name="oid">
/// The Object Identifier
/// </param>
public ManagementAddress(NetworkAddress managementAddress, InterfaceNumbering interfaceSubType, uint ifNumber, string oid)
{
log.Debug("");
// NOTE: We presume that the mgmt address length and the
// object identifier length are zero
var length = TLVTypeLength.TypeLengthLength + MgmtAddressLengthLength + InterfaceNumberSubTypeLength + InterfaceNumberLength + ObjectIdentifierLengthLength;
var bytes = new byte[length];
var offset = 0;
this.tlvData = new ByteArraySegment(bytes, offset, length);
// The lengths are both zero until the values are set
this.AddressLength = 0;
this.ObjIdLength = 0;
this.Type = TLVTypes.ManagementAddress;
this.MgmtAddress = managementAddress;
this.InterfaceSubType = interfaceSubType;
this.InterfaceNumber = ifNumber;
this.ObjectIdentifier = oid;
}
#endregion
#region Properties
/// <value>
/// The Management Address Length
/// </value>
public int AddressLength
{
get { return this.tlvData.Bytes[this.ValueOffset]; }
internal set { this.tlvData.Bytes[this.ValueOffset] = (byte) value; }
}
/// <value>
/// The Management Address Subtype
/// Forward to the MgmtAddress instance
/// </value>
public AddressFamily AddressSubType
{
get { return this.MgmtAddress.AddressFamily; }
}
/// <value>
/// The Management Address
/// </value>
public NetworkAddress MgmtAddress
{
get
{
var offset = this.ValueOffset + MgmtAddressLengthLength;
return new NetworkAddress(this.tlvData.Bytes, offset, this.AddressLength);
}
set
{
var valueLength = value.Length;
var valueBytes = value.Bytes;
// is the new address the same size as the old address?
if(this.AddressLength != valueLength)
{
// need to resize the tlv and shift data fields down
var newLength = TLVTypeLength.TypeLengthLength + MgmtAddressLengthLength + valueLength + InterfaceNumberSubTypeLength + InterfaceNumberLength
+ ObjectIdentifierLengthLength + this.ObjIdLength;
var newBytes = new byte[newLength];
var headerLength = TLVTypeLength.TypeLengthLength + MgmtAddressLengthLength;
var oldStartOfAfterData = this.ValueOffset + MgmtAddressLengthLength + this.AddressLength;
var newStartOfAfterData = TLVTypeLength.TypeLengthLength + MgmtAddressLengthLength + value.Length;
var afterDataLength = InterfaceNumberSubTypeLength + InterfaceNumberLength + ObjectIdentifierLengthLength + this.ObjIdLength;
// copy the data before the mgmt address
Array.Copy(this.tlvData.Bytes, this.tlvData.Offset, newBytes, 0, headerLength);
// copy the data over after the mgmt address over
Array.Copy(this.tlvData.Bytes, oldStartOfAfterData, newBytes, newStartOfAfterData, afterDataLength);
var offset = 0;
this.tlvData = new ByteArraySegment(newBytes, offset, newLength);
// update the address length field
this.AddressLength = valueLength;
}
// copy the new address into the appropriate position in the byte[]
Array.Copy(valueBytes, 0, this.tlvData.Bytes, this.ValueOffset + MgmtAddressLengthLength, valueLength);
}
}
/// <value>
/// Interface Number Sub Type
/// </value>
public InterfaceNumbering InterfaceSubType
{
get { return (InterfaceNumbering) this.tlvData.Bytes[this.ValueOffset + MgmtAddressLengthLength + this.MgmtAddress.Length]; }
set { this.tlvData.Bytes[this.ValueOffset + MgmtAddressLengthLength + this.MgmtAddress.Length] = (byte) value; }
}
private int InterfaceNumberOffset
{
get { return this.ValueOffset + MgmtAddressLengthLength + this.AddressLength + InterfaceNumberSubTypeLength; }
}
/// <value>
/// Interface Number
/// </value>
public uint InterfaceNumber
{
get { return EndianBitConverter.Big.ToUInt32(this.tlvData.Bytes, this.InterfaceNumberOffset); }
set { EndianBitConverter.Big.CopyBytes(value, this.tlvData.Bytes, this.InterfaceNumberOffset); }
}
private int ObjIdLengthOffset
{
get { return this.InterfaceNumberOffset + InterfaceNumberLength; }
}
/// <value>
/// Object ID Length
/// </value>
public byte ObjIdLength
{
get { return this.tlvData.Bytes[this.ObjIdLengthOffset]; }
internal set { this.tlvData.Bytes[this.ObjIdLengthOffset] = value; }
}
private int ObjectIdentifierOffset
{
get { return this.ObjIdLengthOffset + ObjectIdentifierLengthLength; }
}
/// <value>
/// Object ID
/// </value>
public string ObjectIdentifier
{
get { return Encoding.UTF8.GetString(this.tlvData.Bytes, this.ObjectIdentifierOffset, this.ObjIdLength); }
set
{
var oid = Encoding.UTF8.GetBytes(value);
// check for out-of-range sizes
if(oid.Length > maxObjectIdentifierLength) {
throw new ArgumentOutOfRangeException("ObjectIdentifier", "length > maxObjectIdentifierLength of " + maxObjectIdentifierLength);
}
// does the object identifier length match the existing one?
if(this.ObjIdLength != oid.Length)
{
var oldLength = TLVTypeLength.TypeLengthLength + MgmtAddressLengthLength + this.AddressLength + InterfaceNumberSubTypeLength + InterfaceNumberLength
+ ObjectIdentifierLengthLength;
var newLength = oldLength + oid.Length;
var newBytes = new byte[newLength];
// copy the original bytes over
Array.Copy(this.tlvData.Bytes, this.tlvData.Offset, newBytes, 0, oldLength);
var offset = 0;
this.tlvData = new ByteArraySegment(newBytes, offset, newLength);
// update the length
this.ObjIdLength = (byte) value.Length;
}
Array.Copy(oid, 0, this.tlvData.Bytes, this.ObjectIdentifierOffset, oid.Length);
}
}
/// <summary>
/// Convert this Management Address TLV to a string.
/// </summary>
/// <returns>
/// A human readable string
/// </returns>
public override string ToString()
{
return
string.Format(
"[ManagementAddress: AddressLength={0}, AddressSubType={1}, MgmtAddress={2}, InterfaceSubType={3}, InterfaceNumber={4}, ObjIdLength={5}, ObjectIdentifier={6}]",
this.AddressLength, this.AddressSubType, this.MgmtAddress, this.InterfaceSubType, this.InterfaceNumber, this.ObjIdLength, this.ObjectIdentifier);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.WindowsStore;
using System;
#if NETFX_CORE
using System.Linq;
using WinRTLegacy;
#endif
namespace Pathfinding.Serialization {
public class JsonMemberAttribute : System.Attribute {
}
public class JsonOptInAttribute : System.Attribute {
}
/** A very tiny json serializer.
* It is not supposed to have lots of features, it is only intended to be able to serialize graph settings
* well enough.
*/
public class TinyJsonSerializer {
System.Text.StringBuilder output = new System.Text.StringBuilder();
Dictionary<Type, Action<System.Object> > serializers = new Dictionary<Type, Action<object> >();
static readonly System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture;
public static void Serialize (System.Object obj, System.Text.StringBuilder output) {
new TinyJsonSerializer() {
output = output
}.Serialize(obj);
}
TinyJsonSerializer () {
serializers[typeof(float)] = v => output.Append(((float)v).ToString("R", invariantCulture));
serializers[typeof(bool)] = v => output.Append((bool)v ? "true" : "false");
serializers[typeof(Version)] = serializers[typeof(uint)] = serializers[typeof(int)] = v => output.Append(v.ToString());
serializers[typeof(string)] = v => output.AppendFormat("\"{0}\"", v.ToString().Replace("\"", "\\\""));
serializers[typeof(Vector2)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1} }}", ((Vector2)v).x.ToString("R", invariantCulture), ((Vector2)v).y.ToString("R", invariantCulture));
serializers[typeof(Vector3)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1}, \"z\": {2} }}", ((Vector3)v).x.ToString("R", invariantCulture), ((Vector3)v).y.ToString("R", invariantCulture), ((Vector3)v).z.ToString("R", invariantCulture));
serializers[typeof(Pathfinding.Util.Guid)] = v => output.AppendFormat("{{ \"value\": \"{0}\" }}", v.ToString());
serializers[typeof(LayerMask)] = v => output.AppendFormat("{{ \"value\": {0} }}", ((int)(LayerMask)v).ToString());
}
void Serialize (System.Object obj) {
if (obj == null) {
output.Append("null");
return;
}
var type = obj.GetType();
var typeInfo = WindowsStoreCompatibility.GetTypeInfo(type);
if (serializers.ContainsKey(type)) {
serializers[type] (obj);
} else if (typeInfo.IsEnum) {
output.Append('"' + obj.ToString() + '"');
} else if (obj is System.Collections.IList) {
output.Append("[");
var arr = obj as System.Collections.IList;
for (int i = 0; i < arr.Count; i++) {
if (i != 0)
output.Append(", ");
Serialize(arr[i]);
}
output.Append("]");
} else if (obj is UnityEngine.Object) {
SerializeUnityObject(obj as UnityEngine.Object);
} else {
#if NETFX_CORE
var optIn = typeInfo.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonOptInAttribute));
#else
var optIn = typeInfo.GetCustomAttributes(typeof(JsonOptInAttribute), true).Length > 0;
#endif
output.Append("{");
#if NETFX_CORE
var fields = typeInfo.DeclaredFields.Where(f => !f.IsStatic).ToArray();
#else
var fields = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
#endif
bool earlier = false;
foreach (var field in fields) {
if ((!optIn && field.IsPublic) ||
#if NETFX_CORE
field.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonMemberAttribute))
#else
field.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length > 0
#endif
) {
if (earlier) {
output.Append(", ");
}
earlier = true;
output.AppendFormat("\"{0}\": ", field.Name);
Serialize(field.GetValue(obj));
}
}
output.Append("}");
}
}
void QuotedField (string name, string contents) {
output.AppendFormat("\"{0}\": \"{1}\"", name, contents);
}
void SerializeUnityObject (UnityEngine.Object obj) {
// Note that a unityengine can be destroyed as well
if (obj == null) {
Serialize(null);
return;
}
output.Append("{");
QuotedField("Name", obj.name);
output.Append(", ");
QuotedField("Type", obj.GetType().FullName);
//Write scene path if the object is a Component or GameObject
var component = obj as Component;
var go = obj as GameObject;
if (component != null || go != null) {
if (component != null && go == null) {
go = component.gameObject;
}
var helper = go.GetComponent<UnityReferenceHelper>();
if (helper == null) {
Debug.Log("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'");
helper = go.AddComponent<UnityReferenceHelper>();
}
//Make sure it has a unique GUID
helper.Reset();
output.Append(", ");
QuotedField("GUID", helper.GetGUID().ToString());
}
output.Append("}");
}
}
/** A very tiny json deserializer.
* It is not supposed to have lots of features, it is only intended to be able to deserialize graph settings
* well enough. Not much validation of the input is done.
*/
public class TinyJsonDeserializer {
System.IO.TextReader reader;
static readonly System.Globalization.NumberFormatInfo numberFormat = System.Globalization.NumberFormatInfo.InvariantInfo;
/** Deserializes an object of the specified type.
* Will load all fields into the \a populate object if it is set (only works for classes).
*/
public static System.Object Deserialize (string text, Type type, System.Object populate = null) {
return new TinyJsonDeserializer() {
reader = new System.IO.StringReader(text)
}.Deserialize(type, populate);
}
/** Deserializes an object of type tp.
* Will load all fields into the \a populate object if it is set (only works for classes).
*/
System.Object Deserialize (Type tp, System.Object populate = null) {
var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);
if (tpInfo.IsEnum) {
return Enum.Parse(tp, EatField());
} else if (TryEat('n')) {
Eat("ull");
TryEat(',');
return null;
} else if (Type.Equals(tp, typeof(float))) {
return float.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(int))) {
return int.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(uint))) {
return uint.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(bool))) {
return bool.Parse(EatField());
} else if (Type.Equals(tp, typeof(string))) {
return EatField();
} else if (Type.Equals(tp, typeof(Version))) {
return new Version(EatField());
} else if (Type.Equals(tp, typeof(Vector2))) {
Eat("{");
var result = new Vector2();
EatField();
result.x = float.Parse(EatField(), numberFormat);
EatField();
result.y = float.Parse(EatField(), numberFormat);
Eat("}");
return result;
} else if (Type.Equals(tp, typeof(Vector3))) {
Eat("{");
var result = new Vector3();
EatField();
result.x = float.Parse(EatField(), numberFormat);
EatField();
result.y = float.Parse(EatField(), numberFormat);
EatField();
result.z = float.Parse(EatField(), numberFormat);
Eat("}");
return result;
} else if (Type.Equals(tp, typeof(Pathfinding.Util.Guid))) {
Eat("{");
EatField();
var result = Pathfinding.Util.Guid.Parse(EatField());
Eat("}");
return result;
} else if (Type.Equals(tp, typeof(LayerMask))) {
Eat("{");
EatField();
var result = (LayerMask)int.Parse(EatField());
Eat("}");
return result;
} else if (Type.Equals(tp, typeof(List<string>))) {
System.Collections.IList result = new List<string>();
Eat("[");
while (!TryEat(']')) {
result.Add(Deserialize(typeof(string)));
TryEat(',');
}
return result;
} else if (tpInfo.IsArray) {
List<System.Object> ls = new List<System.Object>();
Eat("[");
while (!TryEat(']')) {
ls.Add(Deserialize(tp.GetElementType()));
TryEat(',');
}
var arr = Array.CreateInstance(tp.GetElementType(), ls.Count);
ls.ToArray().CopyTo(arr, 0);
return arr;
} else if (Type.Equals(tp, typeof(Mesh)) || Type.Equals(tp, typeof(Texture2D)) || Type.Equals(tp, typeof(Transform)) || Type.Equals(tp, typeof(GameObject))) {
return DeserializeUnityObject();
} else {
var obj = populate ?? Activator.CreateInstance(tp);
Eat("{");
while (!TryEat('}')) {
var name = EatField();
var field = tp.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
if (field == null) {
SkipFieldData();
} else {
field.SetValue(obj, Deserialize(field.FieldType));
}
TryEat(',');
}
return obj;
}
}
UnityEngine.Object DeserializeUnityObject () {
Eat("{");
var result = DeserializeUnityObjectInner();
Eat("}");
return result;
}
UnityEngine.Object DeserializeUnityObjectInner () {
// Ignore InstanceID field (compatibility only)
var fieldName = EatField();
if (fieldName == "InstanceID") {
EatField();
fieldName = EatField();
}
if (fieldName != "Name") throw new Exception("Expected 'Name' field");
string name = EatField();
if (name == null) return null;
if (EatField() != "Type") throw new Exception("Expected 'Type' field");
string typename = EatField();
// Remove assembly information
if (typename.IndexOf(',') != -1) {
typename = typename.Substring(0, typename.IndexOf(','));
}
// Note calling through assembly is more stable on e.g WebGL
var type = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly.GetType(typename);
type = type ?? WindowsStoreCompatibility.GetTypeInfo(typeof(Transform)).Assembly.GetType(typename);
if (Type.Equals(type, null)) {
Debug.LogError("Could not find type '"+typename+"'. Cannot deserialize Unity reference");
return null;
}
// Check if there is another field there
EatWhitespace();
if ((char)reader.Peek() == '"') {
if (EatField() != "GUID") throw new Exception("Expected 'GUID' field");
string guid = EatField();
foreach (var helper in UnityEngine.Object.FindObjectsOfType<UnityReferenceHelper>()) {
if (helper.GetGUID() == guid) {
if (Type.Equals(type, typeof(GameObject))) {
return helper.gameObject;
} else {
return helper.GetComponent(type);
}
}
}
}
// Try to load from resources
UnityEngine.Object[] objs = Resources.LoadAll(name, type);
for (int i = 0; i < objs.Length; i++) {
if (objs[i].name == name || objs.Length == 1) {
return objs[i];
}
}
return null;
}
void EatWhitespace () {
while (char.IsWhiteSpace((char)reader.Peek()))
reader.Read();
}
void Eat (string s) {
EatWhitespace();
for (int i = 0; i < s.Length; i++) {
var c = (char)reader.Read();
if (c != s[i]) {
throw new Exception("Expected '" + s[i] + "' found '" + c + "'\n\n..." + reader.ReadLine());
}
}
}
System.Text.StringBuilder builder = new System.Text.StringBuilder();
string EatUntil (string c, bool inString) {
builder.Length = 0;
bool escape = false;
while (true) {
var readInt = reader.Peek();
if (!escape && (char)readInt == '"') {
inString = !inString;
}
var readChar = (char)readInt;
if (readInt == -1) {
throw new Exception("Unexpected EOF");
} else if (!escape && readChar == '\\') {
escape = true;
reader.Read();
} else if (!inString && c.IndexOf(readChar) != -1) {
break;
} else {
builder.Append(readChar);
reader.Read();
escape = false;
}
}
return builder.ToString();
}
bool TryEat (char c) {
EatWhitespace();
if ((char)reader.Peek() == c) {
reader.Read();
return true;
}
return false;
}
string EatField () {
var result = EatUntil("\",}]", TryEat('"'));
TryEat('\"');
TryEat(':');
TryEat(',');
return result;
}
void SkipFieldData () {
var indent = 0;
while (true) {
EatUntil(",{}[]", false);
var last = (char)reader.Peek();
switch (last) {
case '{':
case '[':
indent++;
break;
case '}':
case ']':
indent--;
if (indent < 0) return;
break;
case ',':
if (indent == 0) {
reader.Read();
return;
}
break;
default:
throw new System.Exception("Should not reach this part");
}
reader.Read();
}
}
}
}
| |
/*
* 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.Collections.Specialized;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects avatar presence information (for tracking current location and
/// message routing) to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianPresenceServiceConnector")]
public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_serverUrl = String.Empty;
private SimianActivityDetector m_activityDetector;
private bool m_Enabled = false;
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void Close() { }
public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); }
public string Name { get { return "SimianPresenceServiceConnector"; } }
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IPresenceService>(this);
scene.RegisterModuleInterface<IGridUserService>(this);
m_activityDetector.AddRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IPresenceService>(this);
scene.UnregisterModuleInterface<IGridUserService>(this);
m_activityDetector.RemoveRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
#endregion ISharedRegionModule
public SimianPresenceServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("PresenceServices", "");
if (name == Name)
CommonInit(source);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["PresenceService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("PresenceServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
m_Enabled = true;
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI specified, disabling connector");
}
#region IPresenceService
public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
{
m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}",
userID, sessionID, secureSessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddSession" },
{ "UserID", userID.ToString() }
};
if (sessionID != UUID.Zero)
{
requestArgs["SessionID"] = sessionID.ToString();
requestArgs["SecureSessionID"] = secureSessionID.ToString();
}
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutAgent(UUID sessionID)
{
// m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutRegionAgents(UUID regionID)
{
// m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSessions" },
{ "SceneID", regionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString());
return success;
}
public bool ReportAgent(UUID sessionID, UUID regionID)
{
// Not needed for SimianGrid
return true;
}
public PresenceInfo GetAgent(UUID sessionID)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (sessionResponse["Success"].AsBoolean())
{
UUID userID = sessionResponse["UserID"].AsUUID();
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (userResponse["Success"].AsBoolean())
return ResponseToPresenceInfo(sessionResponse, userResponse);
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
}
else
{
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString());
}
return null;
}
public PresenceInfo[] GetAgents(string[] userIDs)
{
List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length);
for (int i = 0; i < userIDs.Length; i++)
{
UUID userID;
if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero)
presences.AddRange(GetSessions(userID));
}
return presences.ToArray();
}
#endregion IPresenceService
#region IGridUserService
public GridUserInfo LoggedIn(string userID)
{
// Never implemented at the sim
return null;
}
public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Logging out user " + userID);
// Remove the session to mark this user offline
if (!LogoutAgent(sessionID))
return false;
// Save our last position as user data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "HomeLocation", SerializeLocation(regionID, position, lookAt) }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
return UpdateSession(sessionID, regionID, lastPosition, lastLookAt);
}
public GridUserInfo GetGridUserInfo(string user)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user);
UUID userID = new UUID(user);
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (userResponse["Success"].AsBoolean())
return ResponseToGridUserInfo(userResponse);
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
return null;
}
#endregion
#region Helpers
private OSDMap GetUserData(UUID userID)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["User"] is OSDMap)
return response;
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString());
return null;
}
private List<PresenceInfo> GetSessions(UUID userID)
{
List<PresenceInfo> presences = new List<PresenceInfo>(1);
OSDMap userResponse = GetUserData(userID);
if (userResponse != null)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSession" },
{ "UserID", userID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
PresenceInfo presence = ResponseToPresenceInfo(response, userResponse);
if (presence != null)
presences.Add(presence);
}
// else
// {
// m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString());
// }
}
return presences;
}
private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
// Save our current location as session data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "UpdateSession" },
{ "SessionID", sessionID.ToString() },
{ "SceneID", regionID.ToString() },
{ "ScenePosition", lastPosition.ToString() },
{ "SceneLookAt", lastLookAt.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());
return success;
}
private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse)
{
if (sessionResponse == null)
return null;
PresenceInfo info = new PresenceInfo();
info.UserID = sessionResponse["UserID"].AsUUID().ToString();
info.RegionID = sessionResponse["SceneID"].AsUUID();
return info;
}
private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse)
{
if (userResponse != null && userResponse["User"] is OSDMap)
{
GridUserInfo info = new GridUserInfo();
info.Online = true;
info.UserID = userResponse["UserID"].AsUUID().ToString();
info.LastRegionID = userResponse["SceneID"].AsUUID();
info.LastPosition = userResponse["ScenePosition"].AsVector3();
info.LastLookAt = userResponse["SceneLookAt"].AsVector3();
OSDMap user = (OSDMap)userResponse["User"];
info.Login = user["LastLoginDate"].AsDate();
info.Logout = user["LastLogoutDate"].AsDate();
DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt);
return info;
}
return null;
}
private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt)
{
return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}";
}
private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt)
{
OSDMap map = null;
try { map = OSDParser.DeserializeJson(location) as OSDMap; }
catch { }
if (map != null)
{
regionID = map["SceneID"].AsUUID();
if (Vector3.TryParse(map["Position"].AsString(), out position) &&
Vector3.TryParse(map["LookAt"].AsString(), out lookAt))
{
return true;
}
}
regionID = UUID.Zero;
position = Vector3.Zero;
lookAt = Vector3.Zero;
return false;
}
public GridUserInfo[] GetGridUserInfo(string[] userIDs)
{
return new GridUserInfo[0];
}
#endregion Helpers
}
}
| |
//
// Copyright DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.ProtocolEvents;
using Cassandra.Requests;
using Cassandra.Responses;
using Cassandra.Serialization;
using Cassandra.Tasks;
namespace Cassandra.Connections
{
internal class ControlConnection : IControlConnection
{
private const string SelectPeers = "SELECT * FROM system.peers";
private const string SelectLocal = "SELECT * FROM system.local WHERE key='local'";
private const CassandraEventType CassandraEventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange;
private static readonly IPAddress BindAllAddress = new IPAddress(new byte[4]);
private readonly Metadata _metadata;
private volatile Host _host;
private volatile IConnectionEndPoint _currentConnectionEndPoint;
private volatile IConnection _connection;
// ReSharper disable once InconsistentNaming
private static readonly Logger _logger = new Logger(typeof(ControlConnection));
private readonly Configuration _config;
private readonly IReconnectionPolicy _reconnectionPolicy;
private IReconnectionSchedule _reconnectionSchedule;
private readonly Timer _reconnectionTimer;
private long _isShutdown;
private int _refreshFlag;
private Task<bool> _reconnectTask;
private readonly Serializer _serializer;
internal const int MetadataAbortTimeout = 5 * 60000;
private readonly IProtocolEventDebouncer _eventDebouncer;
private readonly IEnumerable<object> _contactPoints;
private volatile IReadOnlyList<IConnectionEndPoint> _lastResolvedContactPoints = new List<IConnectionEndPoint>();
/// <summary>
/// Gets the binary protocol version to be used for this cluster.
/// </summary>
public ProtocolVersion ProtocolVersion => _serializer.ProtocolVersion;
/// <inheritdoc />
public Host Host
{
get => _host;
internal set => _host = value;
}
public IConnectionEndPoint EndPoint => _connection?.EndPoint;
public IPEndPoint LocalAddress => _connection?.LocalAddress;
public Serializer Serializer => _serializer;
internal ControlConnection(
IProtocolEventDebouncer eventDebouncer,
ProtocolVersion initialProtocolVersion,
Configuration config,
Metadata metadata,
IEnumerable<object> contactPoints)
{
_metadata = metadata;
_reconnectionPolicy = config.Policies.ReconnectionPolicy;
_reconnectionSchedule = _reconnectionPolicy.NewSchedule();
_reconnectionTimer = new Timer(ReconnectEventHandler, null, Timeout.Infinite, Timeout.Infinite);
_config = config;
_serializer = new Serializer(initialProtocolVersion, config.TypeSerializers);
_eventDebouncer = eventDebouncer;
_contactPoints = contactPoints;
TaskHelper.WaitToComplete(ResolveContactPointsAsync());
}
public void Dispose()
{
Shutdown();
}
/// <inheritdoc />
public async Task InitAsync()
{
ControlConnection._logger.Info("Trying to connect the ControlConnection");
await Connect(true).ConfigureAwait(false);
}
/// <summary>
/// Resolves the contact points to a read only list of <see cref="IConnectionEndPoint"/> which will be used
/// during initialization. Also sets <see cref="_lastResolvedContactPoints"/>.
/// </summary>
private async Task<IReadOnlyList<IConnectionEndPoint>> ResolveContactPointsAsync()
{
var tasksDictionary = await RefreshContactPointResolutionAsync().ConfigureAwait(false);
var lastResolvedContactPoints = tasksDictionary.Values.SelectMany(t => t).ToList();
_lastResolvedContactPoints = lastResolvedContactPoints;
return lastResolvedContactPoints;
}
/// <summary>
/// Resolves all the original contact points to a list of <see cref="IConnectionEndPoint"/>.
/// </summary>
private async Task<IDictionary<object, IEnumerable<IConnectionEndPoint>>> RefreshContactPointResolutionAsync()
{
await _config.EndPointResolver.RefreshContactPointCache().ConfigureAwait(false);
var tasksDictionary = _contactPoints.ToDictionary(c => c, c => _config.EndPointResolver.GetOrResolveContactPointAsync(c));
await Task.WhenAll(tasksDictionary.Values).ConfigureAwait(false);
var resolvedContactPoints =
tasksDictionary.ToDictionary(t => t.Key.ToString(), t => t.Value.Result.Select(ep => ep.GetHostIpEndPointWithFallback()));
_metadata.SetResolvedContactPoints(resolvedContactPoints);
if (!resolvedContactPoints.Any(kvp => kvp.Value.Any()))
{
var hostNames = tasksDictionary.Where(kvp => kvp.Key is string c && !IPAddress.TryParse(c, out _)).Select(kvp => (string) kvp.Key);
throw new NoHostAvailableException($"No host name could be resolved, attempted: {string.Join(", ", hostNames)}");
}
return tasksDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result);
}
/// <summary>
/// Iterates through the query plan or hosts and tries to create a connection.
/// Once a connection is made, topology metadata is refreshed and the ControlConnection is subscribed to Host
/// and Connection events.
/// </summary>
/// <param name="isInitializing">
/// Determines whether the ControlConnection is connecting for the first time as part of the initialization.
/// </param>
/// <exception cref="NoHostAvailableException" />
/// <exception cref="DriverInternalError" />
private async Task Connect(bool isInitializing)
{
IEnumerable<Task<IConnectionEndPoint>> endPointTasks;
var lastResolvedContactPoints = _lastResolvedContactPoints;
if (isInitializing)
{
endPointTasks =
lastResolvedContactPoints
.Select(Task.FromResult)
.Concat(GetHostEnumerable().Select(h => _config.EndPointResolver.GetConnectionEndPointAsync(h, false)));
}
else
{
endPointTasks =
_config.DefaultRequestOptions.LoadBalancingPolicy
.NewQueryPlan(null, null)
.Select(h => _config.EndPointResolver.GetConnectionEndPointAsync(h, false));
}
var triedHosts = new Dictionary<IPEndPoint, Exception>();
foreach (var endPointTask in endPointTasks)
{
var endPoint = await endPointTask.ConfigureAwait(false);
var connection = _config.ConnectionFactory.Create(_serializer, endPoint, _config);
try
{
var version = _serializer.ProtocolVersion;
try
{
await connection.Open().ConfigureAwait(false);
}
catch (UnsupportedProtocolVersionException ex)
{
var nextVersion = _serializer.ProtocolVersion;
connection = await ChangeProtocolVersion(nextVersion, connection, ex, version)
.ConfigureAwait(false);
}
ControlConnection._logger.Info($"Connection established to {connection.EndPoint.EndpointFriendlyName} using protocol " +
$"version {_serializer.ProtocolVersion:D}");
_connection = connection;
await RefreshNodeList(endPoint).ConfigureAwait(false);
var commonVersion = ProtocolVersion.GetHighestCommon(_metadata.Hosts);
if (commonVersion != _serializer.ProtocolVersion)
{
// Current connection will be closed and reopened
connection = await ChangeProtocolVersion(commonVersion, connection).ConfigureAwait(false);
_connection = connection;
}
await SubscribeToServerEvents(connection).ConfigureAwait(false);
await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false);
_host.Down += OnHostDown;
return;
}
catch (Exception ex)
{
// There was a socket or authentication exception or an unexpected error
// NOTE: A host may appear twice iterating by design, see GetHostEnumerable()
triedHosts[endPoint.GetHostIpEndPointWithFallback()] = ex;
connection.Dispose();
}
}
throw new NoHostAvailableException(triedHosts);
}
private async Task<IConnection> ChangeProtocolVersion(ProtocolVersion nextVersion, IConnection previousConnection,
UnsupportedProtocolVersionException ex = null,
ProtocolVersion? previousVersion = null)
{
if (!nextVersion.IsSupported() || nextVersion == previousVersion)
{
nextVersion = nextVersion.GetLowerSupported();
}
if (nextVersion == 0)
{
if (ex != null)
{
// We have downgraded the version until is 0 and none of those are supported
throw ex;
}
// There was no exception leading to the downgrade, signal internal error
throw new DriverInternalError("Connection was unable to STARTUP using protocol version 0");
}
ControlConnection._logger.Info(ex != null
? $"{ex.Message}, trying with version {nextVersion:D}"
: $"Changing protocol version to {nextVersion:D}");
_serializer.ProtocolVersion = nextVersion;
previousConnection.Dispose();
var c = _config.ConnectionFactory.Create(_serializer, previousConnection.EndPoint, _config);
try
{
await c.Open().ConfigureAwait(false);
return c;
}
catch
{
c.Dispose();
throw;
}
}
private async void ReconnectEventHandler(object state)
{
try
{
await Reconnect().ConfigureAwait(false);
}
catch (Exception ex)
{
ControlConnection._logger.Error("An exception was thrown when reconnecting the control connection.", ex);
}
}
internal async Task<bool> Reconnect()
{
var tcs = new TaskCompletionSource<bool>();
var currentTask = Interlocked.CompareExchange(ref _reconnectTask, tcs.Task, null);
if (currentTask != null)
{
// If there is another thread reconnecting, use the same task
return await currentTask.ConfigureAwait(false);
}
Unsubscribe();
var oldConnection = _connection;
try
{
ControlConnection._logger.Info("Trying to reconnect the ControlConnection");
await Connect(false).ConfigureAwait(false);
}
catch (Exception ex)
{
// It failed to reconnect, schedule the timer for next reconnection and let go.
var _ = Interlocked.Exchange(ref _reconnectTask, null);
tcs.TrySetException(ex);
var delay = _reconnectionSchedule.NextDelayMs();
ControlConnection._logger.Error("ControlConnection was not able to reconnect: " + ex);
try
{
_reconnectionTimer.Change((int)delay, Timeout.Infinite);
}
catch (ObjectDisposedException)
{
//Control connection is being disposed
}
// It will throw the same exception that it was set in the TCS
throw;
}
finally
{
if (_connection != oldConnection)
{
oldConnection.Dispose();
}
}
if (Interlocked.Read(ref _isShutdown) > 0L)
{
return false;
}
try
{
_reconnectionSchedule = _reconnectionPolicy.NewSchedule();
tcs.TrySetResult(true);
var _ = Interlocked.Exchange(ref _reconnectTask, null);
ControlConnection._logger.Info("ControlConnection reconnected to host {0}", _host.Address);
}
catch (Exception ex)
{
var _ = Interlocked.Exchange(ref _reconnectTask, null);
ControlConnection._logger.Error("There was an error when trying to refresh the ControlConnection", ex);
tcs.TrySetException(ex);
try
{
_reconnectionTimer.Change((int)_reconnectionSchedule.NextDelayMs(), Timeout.Infinite);
}
catch (ObjectDisposedException)
{
//Control connection is being disposed
}
}
return await tcs.Task.ConfigureAwait(false);
}
private async Task Refresh()
{
if (Interlocked.CompareExchange(ref _refreshFlag, 1, 0) != 0)
{
// Only one refresh at a time
return;
}
var reconnect = false;
try
{
await RefreshNodeList(_currentConnectionEndPoint).ConfigureAwait(false);
await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false);
_reconnectionSchedule = _reconnectionPolicy.NewSchedule();
}
catch (SocketException ex)
{
ControlConnection._logger.Error("There was a SocketException when trying to refresh the ControlConnection", ex);
reconnect = true;
}
catch (Exception ex)
{
ControlConnection._logger.Error("There was an error when trying to refresh the ControlConnection", ex);
}
finally
{
Interlocked.Exchange(ref _refreshFlag, 0);
}
if (reconnect)
{
await Reconnect().ConfigureAwait(false);
}
}
public void Shutdown()
{
if (Interlocked.Increment(ref _isShutdown) != 1)
{
//Only shutdown once
return;
}
var c = _connection;
if (c != null)
{
ControlConnection._logger.Info("Shutting down control connection to {0}", c.EndPoint.EndpointFriendlyName);
c.Dispose();
}
_reconnectionTimer.Change(Timeout.Infinite, Timeout.Infinite);
_reconnectionTimer.Dispose();
}
/// <summary>
/// Gets the next connection and setup the event listener for the host and connection.
/// </summary>
/// <exception cref="SocketException" />
/// <exception cref="DriverInternalError" />
private async Task SubscribeToServerEvents(IConnection connection)
{
connection.CassandraEventResponse += OnConnectionCassandraEvent;
// Register to events on the connection
var response = await connection.Send(new RegisterForEventRequest(ControlConnection.CassandraEventTypes))
.ConfigureAwait(false);
if (!(response is ReadyResponse))
{
throw new DriverInternalError("Expected ReadyResponse, obtained " + response?.GetType().Name);
}
}
/// <summary>
/// Unsubscribe from the current host 'Down' event.
/// </summary>
private void Unsubscribe()
{
var h = _host;
if (h != null)
{
h.Down -= OnHostDown;
}
}
private void OnHostDown(Host h)
{
h.Down -= OnHostDown;
ControlConnection._logger.Warning("Host {0} used by the ControlConnection DOWN", h.Address);
// Queue reconnection to occur in the background
Task.Run(Reconnect).Forget();
}
private async void OnConnectionCassandraEvent(object sender, CassandraEventArgs e)
{
try
{
//This event is invoked from a worker thread (not a IO thread)
if (e is TopologyChangeEventArgs tce)
{
if (tce.What == TopologyChangeEventArgs.Reason.NewNode || tce.What == TopologyChangeEventArgs.Reason.RemovedNode)
{
// Start refresh
await ScheduleHostsRefreshAsync().ConfigureAwait(false);
return;
}
}
if (e is StatusChangeEventArgs args)
{
HandleStatusChangeEvent(args);
return;
}
if (e is SchemaChangeEventArgs ssc)
{
await HandleSchemaChangeEvent(ssc, false).ConfigureAwait(false);
}
}
catch (Exception ex)
{
ControlConnection._logger.Error("Exception thrown while handling cassandra event.", ex);
}
}
/// <inheritdoc />
public Task HandleSchemaChangeEvent(SchemaChangeEventArgs ssc, bool processNow)
{
if (!_config.MetadataSyncOptions.MetadataSyncEnabled)
{
return TaskHelper.Completed;
}
Func<Task> handler;
if (!string.IsNullOrEmpty(ssc.Table))
{
handler = () =>
{
//Can be either a table or a view
_metadata.ClearTable(ssc.Keyspace, ssc.Table);
_metadata.ClearView(ssc.Keyspace, ssc.Table);
return TaskHelper.Completed;
};
}
else if (ssc.FunctionName != null)
{
handler = TaskHelper.ActionToAsync(() => _metadata.ClearFunction(ssc.Keyspace, ssc.FunctionName, ssc.Signature));
}
else if (ssc.AggregateName != null)
{
handler = TaskHelper.ActionToAsync(() => _metadata.ClearAggregate(ssc.Keyspace, ssc.AggregateName, ssc.Signature));
}
else if (ssc.Type != null)
{
return TaskHelper.Completed;
}
else if (ssc.What == SchemaChangeEventArgs.Reason.Dropped)
{
handler = TaskHelper.ActionToAsync(() => _metadata.RemoveKeyspace(ssc.Keyspace));
}
else
{
return ScheduleKeyspaceRefreshAsync(ssc.Keyspace, processNow);
}
return ScheduleObjectRefreshAsync(ssc.Keyspace, processNow, handler);
}
private void HandleStatusChangeEvent(StatusChangeEventArgs e)
{
//The address in the Cassandra event message needs to be translated
var address = TranslateAddress(e.Address);
ControlConnection._logger.Info("Received Node status change event: host {0} is {1}", address, e.What.ToString().ToUpper());
Host host;
if (!_metadata.Hosts.TryGet(address, out host))
{
ControlConnection._logger.Info("Received status change event for host {0} but it was not found", address);
return;
}
var distance = Cluster.RetrieveDistance(host, _config.DefaultRequestOptions.LoadBalancingPolicy);
if (distance != HostDistance.Ignored)
{
// We should not consider events for status changes
// We should trust the pools.
return;
}
if (e.What == StatusChangeEventArgs.Reason.Up)
{
host.BringUpIfDown();
return;
}
host.SetDown();
}
private IPEndPoint TranslateAddress(IPEndPoint value)
{
return _config.AddressTranslator.Translate(value);
}
private async Task RefreshNodeList(IConnectionEndPoint currentEndPoint)
{
ControlConnection._logger.Info("Refreshing node list");
var queriesRs = await Task.WhenAll(QueryAsync(ControlConnection.SelectLocal), QueryAsync(ControlConnection.SelectPeers))
.ConfigureAwait(false);
var localRow = queriesRs[0].FirstOrDefault();
var rsPeers = queriesRs[1];
if (localRow == null)
{
ControlConnection._logger.Error("Local host metadata could not be retrieved");
throw new DriverInternalError("Local host metadata could not be retrieved");
}
_metadata.Partitioner = localRow.GetValue<string>("partitioner");
var host = GetAndUpdateLocalHost(currentEndPoint, localRow);
UpdatePeersInfo(rsPeers, host);
ControlConnection._logger.Info("Node list retrieved successfully");
}
internal Host GetAndUpdateLocalHost(IConnectionEndPoint endPoint, Row row)
{
var hostIpEndPoint = endPoint.GetOrParseHostIpEndPoint(row, _config.AddressTranslator, _config.ProtocolOptions.Port);
var host = _metadata.GetHost(hostIpEndPoint) ?? _metadata.AddHost(hostIpEndPoint);
// Update cluster name, DC and rack for the one node we are connected to
var clusterName = row.GetValue<string>("cluster_name");
if (clusterName != null)
{
_metadata.ClusterName = clusterName;
}
host.SetInfo(row);
SetCurrentConnection(host, endPoint);
return host;
}
internal void UpdatePeersInfo(IEnumerable<Row> rs, Host currentHost)
{
var foundPeers = new HashSet<IPEndPoint>();
foreach (var row in rs)
{
var address = ControlConnection.GetAddressForLocalOrPeerHost(row, _config.AddressTranslator, _config.ProtocolOptions.Port);
if (address == null)
{
ControlConnection._logger.Error("No address found for host, ignoring it.");
continue;
}
foundPeers.Add(address);
var host = _metadata.GetHost(address) ?? _metadata.AddHost(address);
host.SetInfo(row);
}
// Removes all those that seems to have been removed (since we lost the control connection or not valid contact point)
foreach (var address in _metadata.AllReplicas())
{
if (!address.Equals(currentHost.Address) && !foundPeers.Contains(address))
{
_metadata.RemoveHost(address);
}
}
}
private void SetCurrentConnection(Host host, IConnectionEndPoint endPoint)
{
_host = host;
_currentConnectionEndPoint = endPoint;
_metadata.SetCassandraVersion(host.CassandraVersion);
}
/// <summary>
/// Uses system.peers / system.local values to build the Address translator
/// </summary>
internal static IPEndPoint GetAddressForLocalOrPeerHost(Row row, IAddressTranslator translator, int port)
{
var address = row.GetValue<IPAddress>("rpc_address");
if (address == null)
{
return null;
}
if (ControlConnection.BindAllAddress.Equals(address) && !row.IsNull("peer"))
{
address = row.GetValue<IPAddress>("peer");
ControlConnection._logger.Warning(String.Format("Found host with 0.0.0.0 as rpc_address, using listen_address ({0}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", address));
}
return translator.Translate(new IPEndPoint(address, port));
}
/// <summary>
/// Uses the active connection to execute a query
/// </summary>
public IEnumerable<Row> Query(string cqlQuery, bool retry = false)
{
return TaskHelper.WaitToComplete(QueryAsync(cqlQuery, retry), ControlConnection.MetadataAbortTimeout);
}
public async Task<IEnumerable<Row>> QueryAsync(string cqlQuery, bool retry = false)
{
return ControlConnection.GetRowSet(await SendQueryRequestAsync(cqlQuery, retry, QueryProtocolOptions.Default).ConfigureAwait(false));
}
public async Task<Response> SendQueryRequestAsync(string cqlQuery, bool retry, QueryProtocolOptions queryProtocolOptions)
{
var request = new QueryRequest(ProtocolVersion, cqlQuery, false, queryProtocolOptions);
Response response;
try
{
response = await _connection.Send(request).ConfigureAwait(false);
}
catch (SocketException ex)
{
ControlConnection._logger.Error(
$"There was an error while executing on the host {cqlQuery} the query '{_connection.EndPoint.EndpointFriendlyName}'", ex);
if (!retry)
{
throw;
}
// Try reconnect
await Reconnect().ConfigureAwait(false);
// Query with retry set to false
return await SendQueryRequestAsync(cqlQuery, false, queryProtocolOptions).ConfigureAwait(false);
}
return response;
}
/// <summary>
/// Validates that the result contains a RowSet and returns it.
/// </summary>
/// <exception cref="NullReferenceException" />
/// <exception cref="DriverInternalError" />
public static IEnumerable<Row> GetRowSet(Response response)
{
if (response == null)
{
throw new NullReferenceException("Response can not be null");
}
if (!(response is ResultResponse))
{
throw new DriverInternalError("Expected rows, obtained " + response.GetType().FullName);
}
var result = (ResultResponse)response;
if (!(result.Output is OutputRows))
{
throw new DriverInternalError("Expected rows output, obtained " + result.Output.GetType().FullName);
}
return ((OutputRows)result.Output).RowSet;
}
/// <summary>
/// An iterator designed for the underlying collection to change
/// </summary>
private IEnumerable<Host> GetHostEnumerable()
{
var index = 0;
var hosts = _metadata.Hosts.ToArray();
while (index < hosts.Length)
{
yield return hosts[index++];
// Check that the collection changed
var newHosts = _metadata.Hosts.ToCollection();
if (newHosts.Count != hosts.Length)
{
index = 0;
hosts = newHosts.ToArray();
}
}
}
/// <inheritdoc />
public async Task HandleKeyspaceRefreshLaterAsync(string keyspace)
{
var @event = new KeyspaceProtocolEvent(true, keyspace, async () =>
{
await _metadata.RefreshSingleKeyspace(keyspace).ConfigureAwait(false);
});
await _eventDebouncer.HandleEventAsync(@event, false).ConfigureAwait(false);
}
/// <inheritdoc />
public Task ScheduleKeyspaceRefreshAsync(string keyspace, bool processNow)
{
var @event = new KeyspaceProtocolEvent(true, keyspace, () => _metadata.RefreshSingleKeyspace(keyspace));
return processNow
? _eventDebouncer.HandleEventAsync(@event, true)
: _eventDebouncer.ScheduleEventAsync(@event, false);
}
private Task ScheduleObjectRefreshAsync(string keyspace, bool processNow, Func<Task> handler)
{
var @event = new KeyspaceProtocolEvent(false, keyspace, handler);
return processNow
? _eventDebouncer.HandleEventAsync(@event, true)
: _eventDebouncer.ScheduleEventAsync(@event, false);
}
private Task ScheduleHostsRefreshAsync()
{
return _eventDebouncer.ScheduleEventAsync(new ProtocolEvent(Refresh), false);
}
/// <inheritdoc />
public Task ScheduleAllKeyspacesRefreshAsync(bool processNow)
{
var @event = new ProtocolEvent(() => _metadata.RebuildTokenMapAsync(false, true));
return processNow
? _eventDebouncer.HandleEventAsync(@event, true)
: _eventDebouncer.ScheduleEventAsync(@event, false);
}
}
}
| |
// 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 Microsoft.Cci;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EEAssemblyBuilder : PEAssemblyBuilderBase
{
internal readonly ImmutableHashSet<MethodSymbol> Methods;
private readonly NamedTypeSymbol _dynamicOperationContextType;
public EEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
ImmutableArray<MethodSymbol> methods,
ModulePropertiesForSerialization serializationProperties,
ImmutableArray<NamedTypeSymbol> additionalTypes,
NamedTypeSymbol dynamicOperationContextType,
CompilationTestData testData) :
base(
sourceAssembly,
emitOptions,
outputKind: OutputKind.DynamicallyLinkedLibrary,
serializationProperties: serializationProperties,
manifestResources: SpecializedCollections.EmptyEnumerable<ResourceDescription>(),
assemblySymbolMapper: null,
additionalTypes: additionalTypes)
{
Methods = ImmutableHashSet.CreateRange(methods);
_dynamicOperationContextType = dynamicOperationContextType;
if (testData != null)
{
this.SetMethodTestData(testData.Methods);
testData.Module = this;
}
}
protected override IModuleReference TranslateModule(ModuleSymbol symbol, DiagnosticBag diagnostics)
{
var moduleSymbol = symbol as PEModuleSymbol;
if ((object)moduleSymbol != null)
{
var module = moduleSymbol.Module;
// Expose the individual runtime Windows.*.winmd modules as assemblies.
// (The modules were wrapped in a placeholder Windows.winmd assembly
// in MetadataUtilities.MakeAssemblyReferences.)
if (MetadataUtilities.IsWindowsComponent(module.MetadataReader, module.Name) &&
MetadataUtilities.IsWindowsAssemblyName(moduleSymbol.ContainingAssembly.Name))
{
var identity = module.ReadAssemblyIdentityOrThrow();
return new Microsoft.CodeAnalysis.ExpressionEvaluator.AssemblyReference(identity);
}
}
return base.TranslateModule(symbol, diagnostics);
}
internal override bool IgnoreAccessibility => true;
internal override NamedTypeSymbol DynamicOperationContextType => _dynamicOperationContextType;
public override int CurrentGenerationOrdinal => 0;
internal override VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol symbol, MethodSymbol topLevelMethod)
{
var method = symbol as EEMethodSymbol;
if (((object)method != null) && Methods.Contains(method))
{
var defs = GetLocalDefinitions(method.Locals);
return new SlotAllocator(defs);
}
Debug.Assert(!Methods.Contains(symbol));
return null;
}
private static ImmutableArray<LocalDefinition> GetLocalDefinitions(ImmutableArray<LocalSymbol> locals)
{
var builder = ArrayBuilder<LocalDefinition>.GetInstance();
foreach (var local in locals)
{
if (local.DeclarationKind == LocalDeclarationKind.Constant)
{
continue;
}
var def = ToLocalDefinition(local, builder.Count);
Debug.Assert(((EELocalSymbol)local).Ordinal == def.SlotIndex);
builder.Add(def);
}
return builder.ToImmutableAndFree();
}
private static LocalDefinition ToLocalDefinition(LocalSymbol local, int index)
{
// See EvaluationContext.GetLocals.
TypeSymbol type;
LocalSlotConstraints constraints;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable)
{
type = ((PointerTypeSymbol)local.Type).PointedAtType;
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
}
else
{
type = local.Type;
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
((local.RefKind == RefKind.None) ? LocalSlotConstraints.None : LocalSlotConstraints.ByRef);
}
return new LocalDefinition(
local,
local.Name,
(Cci.ITypeReference)type,
slot: index,
synthesizedKind: (SynthesizedLocalKind)local.SynthesizedKind,
id: LocalDebugId.None,
pdbAttributes: Cci.PdbWriter.DefaultLocalAttributesValue,
constraints: constraints,
isDynamic: false,
dynamicTransformFlags: ImmutableArray<TypedConstant>.Empty);
}
private sealed class SlotAllocator : VariableSlotAllocator
{
private readonly ImmutableArray<LocalDefinition> _locals;
internal SlotAllocator(ImmutableArray<LocalDefinition> locals)
{
_locals = locals;
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_locals);
}
public override LocalDefinition GetPreviousLocal(
Cci.ITypeReference type,
ILocalSymbolInternal symbol,
string nameOpt,
SynthesizedLocalKind synthesizedKind,
LocalDebugId id,
uint pdbAttributes,
LocalSlotConstraints constraints,
bool isDynamic,
ImmutableArray<TypedConstant> dynamicTransformFlags)
{
var local = symbol as EELocalSymbol;
if ((object)local == null)
{
return null;
}
return _locals[local.Ordinal];
}
public override string PreviousStateMachineTypeName
{
get { return null; }
}
public override bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override int PreviousHoistedLocalSlotCount
{
get { return 0; }
}
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId)
{
closureId = default(DebugId);
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId)
{
lambdaId = default(DebugId);
return false;
}
public override int PreviousAwaiterSlotCount
{
get { return 0; }
}
public override DebugId? MethodId
{
get
{
return null;
}
}
}
}
}
| |
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using DbLocalizationProvider.Cache;
using DbLocalizationProvider.Export;
using DbLocalizationProvider.Import;
using DbLocalizationProvider.Logging;
using DbLocalizationProvider.Sync;
namespace DbLocalizationProvider
{
/// <summary>
/// Context to configure various localization provider features and behavior
/// </summary>
public class ConfigurationContext
{
/// <summary>
/// Value indicating default culture for resources registered from code.
/// </summary>
public const string CultureForTranslationsFromCode = "";
internal readonly BaseCacheManager BaseCacheManager = new BaseCacheManager(new InMemoryCache());
/// <summary>
/// Creates new instance of configuration settings.
/// </summary>
public ConfigurationContext()
{
TypeFactory = new TypeFactory(this);
}
/// <summary>
/// Gets or sets the callback for enabling or disabling localization. If this returns <c>false</c> - resource key will
/// be returned. Default <c>true</c>.
/// </summary>
/// <value>
/// <c>true</c> to enable localization; otherwise - <c>false</c>.
/// </value>
public Func<bool> EnableLocalization { get; set; } = () => true;
/// <summary>
/// Gets or sets callback to call in order to enable ir disable legacy mode.
/// Legacy mode will ensure that if resource value starts with "/" symbol ModelMetadataProvider will try to look for
/// this XPath resource in localization provider collection once again.
/// This will make it possible to continue use *old* resource keys:
/// [DisplayName("/xpath/to/some/resource")]
///
/// Default <c>false</c>.
/// </summary>
/// <value>
/// Return <c>true</c> to enable legacy mode translations.
/// </value>
public Func<bool> EnableLegacyMode { get; set; } = () => false;
/// <summary>
/// Gets or sets the flag to control localized models discovery and registration during app startup or whenever you initialize provider.
/// Default <c>true</c>.
/// </summary>
/// <value>
/// Discovers and registers localized models.
/// </value>
public bool DiscoverAndRegisterResources { get; set; } = true;
/// <summary>
/// Forces type scanner to load all referenced assemblies. When enabled, scanner is not relying on current
/// AppDomain.GetAssemblies but checks referenced assemblies recursively.
/// Default <c>false</c>.
/// </summary>
/// <value>
/// By default this feature is disabled.
/// </value>
public bool ScanAllAssemblies { get; set; } = false;
/// <summary>
/// Settings for model metadata providers.
/// </summary>
public ModelMetadataProvidersConfiguration ModelMetadataProviders { get; set; } =
new ModelMetadataProvidersConfiguration();
/// <summary>
/// Gets or sets the default resource culture to register translations for newly discovered resources.
/// </summary>
/// <value>
/// The default resource culture for translations.
/// </value>
public CultureInfo DefaultResourceCulture { get; set; }
/// <summary>
/// Gets or sets a value indicating whether cache should be populated during startup (default = true).
/// Default <c>true</c>.
/// </summary>
/// <value>
/// <c>true</c> if cache should be populated; otherwise, <c>false</c>.
/// </value>
public bool PopulateCacheOnStartup { get; set; } = true;
/// <summary>
/// Returns type factory used internally for creating new services or handlers for commands.
/// </summary>
public TypeFactory TypeFactory { get; internal set; }
/// <summary>
/// Gets or sets callback whether lookup resource by requested key.
/// Use with caution. This is optimization workaround for the cases when you need to filter out and allow some of the resources to pass-through
/// for <see cref="Queries.GetTranslation.Query" /> query.
/// </summary>
/// <remarks>Return <c>true</c> if you want to continue translation lookup for given resource key</remarks>
public Func<string, bool> ResourceLookupFilter { internal get; set; }
/// <summary>
/// Gets or sets cache manager used to store resources and translations
/// </summary>
public ICacheManager CacheManager
{
get => BaseCacheManager;
set
{
if (value != null)
{
BaseCacheManager.SetInnerManager(value);
}
}
}
/// <summary>
/// Gets or sets flag to enable or disable invariant culture fallback (to use resource values discovered and registered from code).
/// Default <c>false</c>.
/// </summary>
public bool EnableInvariantCultureFallback { get; set; } = false;
/// <summary>
/// Gets or sets filter to apply for assembly list in application for reducing time spent during scanning.
/// </summary>
public Func<Assembly, bool> AssemblyScanningFilter { get; set; } =
a => !a.IsDynamic
&& !a.FullName.StartsWith("Microsoft")
&& !a.FullName.StartsWith("mscorlib")
&& !a.FullName.StartsWith("System")
&& !a.FullName.StartsWith("EPiServer")
&& !a.FullName.StartsWith("EntityFramework")
&& !a.FullName.StartsWith("Newtonsoft");
/// <summary>
/// Gets or sets value enabling or disabling diagnostics for localization provider (e.g. missing keys will be written
/// to log file).
/// Default <c>false</c>.
/// </summary>
public bool DiagnosticsEnabled { get; set; } = false;
/// <summary>
/// Gets or sets list of custom attributes that should be discovered and registered during startup scanning.
/// </summary>
public ICollection<CustomAttributeDescriptor> CustomAttributes { get; set; } = new List<CustomAttributeDescriptor>();
/// <summary>
/// Gets or sets collection of foreign resources. Foreign resource descriptors are used to include classes without
/// <c>[LocalizedResource]</c> or <c>[LocalizedModel]</c> attributes.
/// </summary>
public ICollection<ForeignResourceDescriptor> ForeignResources { get; set; } = new List<ForeignResourceDescriptor>();
/// <summary>
/// Gets or sets settings used for export of the resources.
/// </summary>
public ExportSettings Export { get; set; } = new ExportSettings();
/// <summary>
/// Gets or sets settings to be used during resource import.
/// </summary>
public ImportSettings Import { get; set; } = new ImportSettings();
/// <summary>
/// Gets list of all known type scanners.
/// </summary>
public List<IResourceTypeScanner> TypeScanners { get; } = new List<IResourceTypeScanner>();
internal readonly FallbackLanguagesCollection FallbackList = new FallbackLanguagesCollection();
/// <summary>
/// This is your last chance to lookup translations in other languages if there is none for the requested one.
/// </summary>
public FallbackLanguages FallbackLanguages => FallbackList.GetFallbackLanguages("default");
/// <summary>
/// Gets or sets the logger to be used by the localization provider library. Depending on runtime platform specific implementations may use
/// this interface to add adapter for their logging infra.
/// </summary>
public ILogger Logger { get; set; } = new NullLogger();
/// <summary>
/// If you are looking for a way to allow other characters in resource key name - this is the property to set.
/// </summary>
public Regex ResourceKeyNameFilter { get; set; } = new Regex("^[.@+\\\"\\=\\/\\[\\]a-zA-Z0-9]+$");
/// <summary>
/// You can set provider that would return manual resources to sync.
/// </summary>
public IManualResourceProvider ManualResourceProvider { get; set; }
/// <summary>
/// Wanna chill a bit? The use this flexible and relaxed refactored resource sync mode.
/// By enabling this you are telling sync process not to panic if there is already existing refactored resources in target db.
/// This easily can happen if you switch between two branches from which one of them contains refactored code already.
/// Default <c>false</c>.
/// </summary>
public bool FlexibleRefactoringMode { get; set; } = false;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.ProviderBase
{
// set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup
// when not found a new pool entry is created and potentially added
// DbConnectionPoolGroup starts in the Active state
// Open calls DbConnectionFactory.GetConnectionPool
// if the existing pool entry is Disabled, GetConnectionPoolGroup is called for a new entry
// DbConnectionFactory.GetConnectionPool calls DbConnectionPoolGroup.GetConnectionPool
// DbConnectionPoolGroup.GetConnectionPool will return pool for the current identity
// or null if identity is restricted or pooling is disabled or state is disabled at time of add
// state changes are Active->Active, Idle->Active
// DbConnectionFactory.PruneConnectionPoolGroups calls Prune
// which will QueuePoolForRelease on all empty pools
// and once no pools remain, change state from Active->Idle->Disabled
// Once Disabled, factory can remove its reference to the pool entry
sealed internal class DbConnectionPoolGroup
{
private readonly DbConnectionOptions _connectionOptions;
private readonly DbConnectionPoolKey _poolKey;
private readonly DbConnectionPoolGroupOptions _poolGroupOptions;
private ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> _poolCollection;
private int _state; // see PoolGroupState* below
private DbConnectionPoolGroupProviderInfo _providerInfo;
private DbMetaDataFactory _metaDataFactory;
// always lock this before changing _state, we don't want to move out of the 'Disabled' state
// PoolGroupStateUninitialized = 0;
private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open
private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear
private const int PoolGroupStateDisabled = 4; // factory pool entry pruning method
internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions)
{
Debug.Assert(null != connectionOptions, "null connection options");
_connectionOptions = connectionOptions;
_poolKey = key;
_poolGroupOptions = poolGroupOptions;
// always lock this object before changing state
// HybridDictionary does not create any sub-objects until add
// so it is safe to use for non-pooled connection as long as
// we check _poolGroupOptions first
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
_state = PoolGroupStateActive;
}
internal DbConnectionOptions ConnectionOptions => _connectionOptions;
internal DbConnectionPoolKey PoolKey => _poolKey;
internal DbConnectionPoolGroupProviderInfo ProviderInfo
{
get
{
return _providerInfo;
}
set
{
_providerInfo = value;
if (null != value)
{
_providerInfo.PoolGroup = this;
}
}
}
internal bool IsDisabled => (PoolGroupStateDisabled == _state);
internal DbConnectionPoolGroupOptions PoolGroupOptions => _poolGroupOptions;
internal DbMetaDataFactory MetaDataFactory
{
get
{
return _metaDataFactory;
}
set
{
_metaDataFactory = value;
}
}
internal int Clear()
{
// must be multi-thread safe with competing calls by Clear and Prune via background thread
// will return the number of connections in the group after clearing has finished
// First, note the old collection and create a new collection to be used
ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null;
lock (this)
{
if (_poolCollection.Count > 0)
{
oldPoolCollection = _poolCollection;
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
}
}
// Then, if a new collection was created, release the pools from the old collection
if (oldPoolCollection != null)
{
foreach (var entry in oldPoolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, true);
}
}
}
// Finally, return the pool collection count - this may be non-zero if something was added while we were clearing
return _poolCollection.Count;
}
internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory)
{
// When this method returns null it indicates that the connection
// factory should not use pooling.
// We don't support connection pooling on Win9x;
// PoolGroupOptions will only be null when we're not supposed to pool
// connections.
DbConnectionPool pool = null;
if (null != _poolGroupOptions)
{
DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity;
if (_poolGroupOptions.PoolByIdentity)
{
// if we're pooling by identity (because integrated security is
// being used for these connections) then we need to go out and
// search for the connectionPool that matches the current identity.
currentIdentity = DbConnectionPoolIdentity.GetCurrent();
// If the current token is restricted in some way, then we must
// not attempt to pool these connections.
if (currentIdentity.IsRestricted)
{
currentIdentity = null;
}
}
if (null != currentIdentity)
{
if (!_poolCollection.TryGetValue(currentIdentity, out pool)) // find the pool
{
lock (this)
{
// Did someone already add it to the list?
if (!_poolCollection.TryGetValue(currentIdentity, out pool))
{
DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
if (MarkPoolGroupAsActive())
{
// If we get here, we know for certain that we there isn't
// a pool that matches the current identity, so we have to
// add the optimistically created one
newPool.Startup(); // must start pool before usage
bool addResult = _poolCollection.TryAdd(currentIdentity, newPool);
Debug.Assert(addResult, "No other pool with current identity should exist at this point");
pool = newPool;
}
else
{
// else pool entry has been disabled so don't create new pools
Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");
// don't need to call connectionFactory.QueuePoolForRelease(newPool) because
// pool callbacks were delayed and no risk of connections being created
newPool.Shutdown();
}
}
else
{
// else found an existing pool to use instead
Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
}
}
}
// the found pool could be in any state
}
}
if (null == pool)
{
lock (this)
{
// keep the pool entry state active when not pooling
MarkPoolGroupAsActive();
}
}
return pool;
}
private bool MarkPoolGroupAsActive()
{
// when getting a connection, make the entry active if it was idle (but not disabled)
// must always lock this before calling
if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateActive;
}
return (PoolGroupStateActive == _state);
}
internal bool Prune()
{
// must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread
// must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove
// to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry
lock (this)
{
if (_poolCollection.Count > 0)
{
var newPoolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
foreach (var entry in _poolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
// Actually prune the pool if there are no connections in the pool and no errors occurred.
// Empty pool during pruning indicates zero or low activity, but
// an error state indicates the pool needs to stay around to
// throttle new connection attempts.
if ((!pool.ErrorOccurred) && (0 == pool.Count))
{
// Order is important here. First we remove the pool
// from the collection of pools so no one will try
// to use it while we're processing and finally we put the
// pool into a list of pools to be released when they
// are completely empty.
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, false);
}
else
{
newPoolCollection.TryAdd(entry.Key, entry.Value);
}
}
}
_poolCollection = newPoolCollection;
}
// must be pruning thread to change state and no connections
// otherwise pruning thread risks making entry disabled soon after user calls ClearPool
if (0 == _poolCollection.Count)
{
if (PoolGroupStateActive == _state)
{
_state = PoolGroupStateIdle;
}
else if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateDisabled;
}
}
return (PoolGroupStateDisabled == _state);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using ExtensionLoader;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.Packets;
namespace Simian.Extensions
{
public class ImageDownload
{
public const int FIRST_IMAGE_PACKET_SIZE = 600;
public const int IMAGE_PACKET_SIZE = 1000;
public AssetTexture Texture;
public int DiscardLevel;
public float Priority;
public int CurrentPacket;
public int StopPacket;
public ImageDownload(AssetTexture texture, int discardLevel, float priority, int packet)
{
Texture = texture;
Update(discardLevel, priority, packet);
}
/// <summary>
/// Updates an image transfer with new information and recalculates
/// offsets
/// </summary>
/// <param name="discardLevel">New requested discard level</param>
/// <param name="priority">New requested priority</param>
/// <param name="packet">New requested packet offset</param>
public void Update(int discardLevel, float priority, int packet)
{
Priority = priority;
DiscardLevel = Utils.Clamp(discardLevel, 0, Texture.LayerInfo.Length - 1);
StopPacket = GetPacketForBytePosition(Texture.LayerInfo[(Texture.LayerInfo.Length - 1) - DiscardLevel].End);
CurrentPacket = Utils.Clamp(packet, 1, TexturePacketCount());
}
/// <summary>
/// Returns the total number of packets needed to transfer this texture,
/// including the first packet of size FIRST_IMAGE_PACKET_SIZE
/// </summary>
/// <returns>Total number of packets needed to transfer this texture</returns>
public int TexturePacketCount()
{
return ((Texture.AssetData.Length - FIRST_IMAGE_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
}
/// <summary>
/// Returns the current byte offset for this transfer, calculated from
/// the CurrentPacket
/// </summary>
/// <returns>Current byte offset for this transfer</returns>
public int CurrentBytePosition()
{
return FIRST_IMAGE_PACKET_SIZE + (CurrentPacket - 1) * IMAGE_PACKET_SIZE;
}
/// <summary>
/// Returns the size, in bytes, of the last packet. This will be somewhere
/// between 1 and IMAGE_PACKET_SIZE bytes
/// </summary>
/// <returns>Size of the last packet in the transfer</returns>
public int LastPacketSize()
{
return Texture.AssetData.Length - (FIRST_IMAGE_PACKET_SIZE + ((TexturePacketCount() - 2) * IMAGE_PACKET_SIZE));
}
/// <summary>
/// Find the packet number that contains a given byte position
/// </summary>
/// <param name="bytePosition">Byte position</param>
/// <returns>Packet number that contains the given byte position</returns>
int GetPacketForBytePosition(int bytePosition)
{
return ((bytePosition - FIRST_IMAGE_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE);
}
}
public class ImageDelivery : IExtension<Simian>
{
Simian server;
Dictionary<UUID, ImageDownload> CurrentDownloads = new Dictionary<UUID, ImageDownload>();
BlockingQueue<ImageDownload> CurrentDownloadQueue = new BlockingQueue<ImageDownload>();
public ImageDelivery()
{
}
public void Start(Simian server)
{
this.server = server;
server.UDP.RegisterPacketCallback(PacketType.RequestImage, new PacketCallback(RequestImageHandler));
}
public void Stop()
{
}
void RequestImageHandler(Packet packet, Agent agent)
{
RequestImagePacket request = (RequestImagePacket)packet;
for (int i = 0; i < request.RequestImage.Length; i++)
{
RequestImagePacket.RequestImageBlock block = request.RequestImage[i];
ImageDownload download;
bool downloadFound = CurrentDownloads.TryGetValue(block.Image, out download);
if (downloadFound)
{
lock (download)
{
if (block.DiscardLevel == -1 && block.DownloadPriority == 0.0f)
{
Logger.DebugLog(String.Format("Image download {0} is aborting", block.Image));
}
else
{
if (block.DiscardLevel < download.DiscardLevel)
Logger.DebugLog(String.Format("Image download {0} is changing from DiscardLevel {1} to {2}",
block.Image, download.DiscardLevel, block.DiscardLevel));
if (block.DownloadPriority != download.Priority)
Logger.DebugLog(String.Format("Image download {0} is changing from Priority {1} to {2}",
block.Image, download.Priority, block.DownloadPriority));
if (block.Packet != download.CurrentPacket)
Logger.DebugLog(String.Format("Image download {0} is changing from Packet {1} to {2}",
block.Image, download.CurrentPacket, block.Packet));
}
// Update download
download.Update(block.DiscardLevel, block.DownloadPriority, (int)block.Packet);
}
}
else if (block.DiscardLevel == -1 && block.DownloadPriority == 0.0f)
{
// Aborting a download we are not tracking, ignore
Logger.DebugLog(String.Format("Aborting an image download for untracked image " + block.Image.ToString()));
}
else
{
bool bake = ((ImageType)block.Type == ImageType.Baked);
// New download, check if we have this image
Asset asset;
if (server.Assets.TryGetAsset(block.Image, out asset) && asset is AssetTexture)
{
download = new ImageDownload((AssetTexture)asset, block.DiscardLevel, block.DownloadPriority,
(int)block.Packet);
Logger.DebugLog(String.Format(
"Starting new download for {0}, DiscardLevel: {1}, Priority: {2}, Start: {3}, End: {4}, Total: {5}",
block.Image, block.DiscardLevel, block.DownloadPriority, download.CurrentPacket, download.StopPacket,
download.TexturePacketCount()));
// Send initial data
ImageDataPacket data = new ImageDataPacket();
data.ImageID.Codec = (byte)ImageCodec.J2C;
data.ImageID.ID = download.Texture.AssetID;
data.ImageID.Packets = (ushort)download.TexturePacketCount();
data.ImageID.Size = (uint)download.Texture.AssetData.Length;
// The first bytes of the image are always sent in the ImageData packet
data.ImageData = new ImageDataPacket.ImageDataBlock();
int imageDataSize = (download.Texture.AssetData.Length >= ImageDownload.FIRST_IMAGE_PACKET_SIZE) ?
ImageDownload.FIRST_IMAGE_PACKET_SIZE : download.Texture.AssetData.Length;
data.ImageData.Data = new byte[imageDataSize];
Buffer.BlockCopy(download.Texture.AssetData, 0, data.ImageData.Data, 0, imageDataSize);
server.UDP.SendPacket(agent.AgentID, data, PacketCategory.Texture);
// Check if ImagePacket packets need to be sent to complete this transfer
if (download.CurrentPacket <= download.StopPacket)
{
// Insert this download into the dictionary
lock (CurrentDownloads)
CurrentDownloads[block.Image] = download;
// Send all of the remaining packets
ThreadPool.QueueUserWorkItem(
delegate(object obj)
{
while (download.CurrentPacket <= download.StopPacket)
{
if (download.Priority == 0.0f && download.DiscardLevel == -1)
break;
lock (download)
{
int imagePacketSize = (download.CurrentPacket == download.TexturePacketCount() - 1) ?
download.LastPacketSize() : ImageDownload.IMAGE_PACKET_SIZE;
ImagePacketPacket transfer = new ImagePacketPacket();
transfer.ImageID.ID = block.Image;
transfer.ImageID.Packet = (ushort)download.CurrentPacket;
transfer.ImageData.Data = new byte[imagePacketSize];
Buffer.BlockCopy(download.Texture.AssetData, download.CurrentBytePosition(),
transfer.ImageData.Data, 0, imagePacketSize);
server.UDP.SendPacket(agent.AgentID, transfer, PacketCategory.Texture);
++download.CurrentPacket;
}
}
Logger.DebugLog("Completed image transfer for " + block.Image.ToString());
// Transfer is complete, remove the reference
lock (CurrentDownloads)
CurrentDownloads.Remove(block.Image);
}
);
}
}
else
{
Logger.Log("Request for a missing texture " + block.Image.ToString(), Helpers.LogLevel.Warning);
ImageNotInDatabasePacket notfound = new ImageNotInDatabasePacket();
notfound.ImageID.ID = block.Image;
server.UDP.SendPacket(agent.AgentID, notfound, PacketCategory.Texture);
}
}
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System;
using Random = UnityEngine.Random;
public class PlayerShootingScript : MonoBehaviour {
public const float AimingTime = 0.75f;
public int BurstCount = 8;
public float ShotCooldown = 0.045f;
public float ReloadTime = 0.45f;
public float BurstSpread = 1.5f;
public float ShotgunSpreadBase = 0.375f;
public float ShotgunSpread = 10;
public float ShotgunBulletSpeedMultiplier = 0.25f;
public float ShotgunHomingSpeed = 0.675f;
public float CannonChargeTime = 0.5f;
public float HeatAccuracyFudge = 0.5f;
public AudioSource reloadSound;
public AudioSource targetSound;
public AudioSource pepperGunSound;
public AudioSource burstGunSound;
public BulletScript bulletPrefab;
public BulletScript cannonBulletPrefab;
public Transform gun;
public Texture2D cannonIndicator;
public AnimationCurve cannonOuterScale;
public AnimationCurve cannonInnerScale;
Material mat;
public float heat = 0.0f;
float cooldownLeft = 0.0f;
int bulletsLeft;
public float GunRotationSmoothingSpeed = 8.0f;
WeaponIndicatorScript weaponIndicator;
public List<WeaponIndicatorScript.PlayerData> targets;
CameraScript playerCamera;
PlayerScript playerScript;
private Vector3 firingDirection;
void Awake() {
bulletsLeft = BurstCount;
playerCamera = GetComponentInChildren<CameraScript>();
weaponIndicator = Camera.main.GetComponent<WeaponIndicatorScript>();
targets = weaponIndicator.Targets;
playerScript = GetComponent<PlayerScript>();
}
WeaponIndicatorScript.PlayerData GetFirstTarget() {
return targets.Where(x => x.SinceInCrosshair >= AimingTime)
.OrderBy(x => Guid.NewGuid())
.First();
}
void Update() {
Vector3 actualTargetPosition = playerCamera.GetTargetPosition();
firingDirection = (actualTargetPosition - gun.transform.position).normalized;
Vector3 gunRotationAngles = Quaternion.FromToRotation(Vector3.forward, firingDirection).eulerAngles;
Quaternion desiredGunRotation = Quaternion.Euler(gunRotationAngles.x, gunRotationAngles.y, 0);
gun.transform.rotation = Quaternion.Slerp(gun.transform.rotation, desiredGunRotation, Time.deltaTime * GunRotationSmoothingSpeed);
if (playerScript.paused) {
bulletsLeft = BurstCount;
}
if (networkView.isMine && Screen.lockCursor && !playerScript.paused) {
cooldownLeft = Mathf.Max(0, cooldownLeft - Time.deltaTime);
heat = Mathf.Clamp01(heat - Time.deltaTime);
weaponIndicator.CooldownStep = 1 - Math.Min(Math.Max(cooldownLeft - ShotCooldown, 0) / ReloadTime, 1);
if (cooldownLeft == 0) {
// Shotgun
if (Input.GetButton("Alternate Fire")) {
playerScript.health.ShotFired();
// find homing target(s)
IEnumerable<WeaponIndicatorScript.PlayerData> aimedAt = targets.Where(x => x.SinceInCrosshair >= AimingTime);
int bulletsShot = bulletsLeft;
bool first = true;
while (bulletsLeft > 0) {
if (!aimedAt.Any())
DoHomingShot(ShotgunSpread, null, 0, first);
else {
WeaponIndicatorScript.PlayerData pd = aimedAt.OrderBy(x => Guid.NewGuid()).First();
DoHomingShot(ShotgunSpread, pd.Script, Mathf.Clamp01(pd.SinceInCrosshair / AimingTime) * ShotgunHomingSpeed, first);
}
cooldownLeft += ShotCooldown;
first = false;
}
cooldownLeft += ReloadTime;
Vector3 recoilImpulse = -gun.forward * ((float)bulletsShot / BurstCount);
recoilImpulse *= playerScript.controller.isGrounded ? 25 : 87.5f;
recoilImpulse.y *= playerScript.controller.isGrounded ? 0.1f : 0.375f;
playerScript.AddRecoil(recoilImpulse);
}
// Burst
else if (Input.GetButton("Fire")) // burst fire
{
playerScript.health.ShotFired();
DoShot(BurstSpread);
cooldownLeft += ShotCooldown;
if (bulletsLeft <= 0)
cooldownLeft += ReloadTime;
}
if (bulletsLeft != BurstCount && Input.GetButton("Reload")) {
bulletsLeft = BurstCount;
reloadSound.Play();
cooldownLeft += ReloadTime;
}
}
if (bulletsLeft <= 0) {
bulletsLeft = BurstCount;
reloadSound.Play();
}
Vector2 screenCenter = new Vector2(Screen.width / 2f, Screen.height / 2f);
float allowedDistance = 130 * Screen.height / 1500f;
foreach (WeaponIndicatorScript.PlayerData v in targets) v.Found = false;
// Test for players in crosshair
foreach (KeyValuePair<NetworkPlayer, PlayerRegistry.PlayerInfo> info in PlayerRegistry.All()) {
PlayerScript player = info.Value.Player;
// Is targeting self?
if (player == playerScript) continue;
Vector3 position = player.transform.position;
Vector3 screenPos = Camera.main.WorldToScreenPoint(position);
if (player.health.Health > 0 && screenPos.z > 0 && (new Vector2(screenPos.x, screenPos.y) - screenCenter).magnitude < allowedDistance) {
WeaponIndicatorScript.PlayerData data;
if ((data = targets.FirstOrDefault(x => x.Script == player)) == null) {
targets.Add(data = new WeaponIndicatorScript.PlayerData { Script = player, WasLocked = false });
}
data.ScreenPosition = new Vector2(screenPos.x,screenPos.y);
data.SinceInCrosshair += Time.deltaTime;
data.Found = true;
if (!data.WasLocked && data.Locked) { // Send target notification
targetSound.Play();
data.Script.networkView.RPC("Targeted", RPCMode.All, playerScript.owner);
}
}
}
CheckTargets();
}
}
void OnApplicationQuit() {
CheckTargets();
}
public void CheckTargets() {
if (targets.Count > 0) {
for (int i = 0; i < targets.Count; i++) {
if (targets[i].Script != null) {
if (targets[i].WasLocked && !targets[i].Found)
targets[i].Script.networkView.RPC("Untargeted", RPCMode.All, playerScript.owner);
targets[i].WasLocked = targets[i].Locked;
if (!targets[i].Found || playerScript.health.Health < 1 || targets[i].Script == null) // Is player in target list dead, or unseen? Am I dead?
targets.RemoveAt(i);
} else {
targets.RemoveAt(i);
}
}
}
}
void DoShot(float spread) {
bulletsLeft -= 1;
spread += heat * HeatAccuracyFudge;
heat += 0.25f;
float roll = Random.value * 360;
Quaternion spreadRotation = Quaternion.Euler(0, 0, roll) *
Quaternion.Euler(Random.value * spread, 0, 0) *
Quaternion.Euler(0, 0, -roll);
Quaternion firingRotation = Quaternion.FromToRotation(Vector3.forward, firingDirection);
networkView.RPC("Shoot", RPCMode.All,
gun.position + firingDirection * 4.0f, firingRotation * spreadRotation,
Network.player);
}
public void InstantReload() {
bulletsLeft = BurstCount;
}
void DoHomingShot(float spread, PlayerScript target, float homing, bool doSound) {
bulletsLeft -= 1;
spread *= (ShotgunSpreadBase + homing * 5);
float roll = RandomHelper.Between(homing * 90, 360 - homing * 90);
Quaternion spreadRotation = Quaternion.Euler(0, 0, roll) *
Quaternion.Euler(Random.value * spread, 0, 0) *
Quaternion.Euler(0, 0, -roll);
Quaternion firingRotation = Quaternion.FromToRotation(Vector3.forward, firingDirection);
Vector3 lastKnownPosition = Vector3.zero;
NetworkPlayer targetOwner = Network.player;
if (target != null) {
targetOwner = target.owner;
lastKnownPosition = target.transform.position;
}
networkView.RPC("ShootHoming", RPCMode.All,
gun.position + firingDirection * 4.0f, firingRotation * spreadRotation,
Network.player, targetOwner, lastKnownPosition, homing, doSound);
}
[RPC]
void Shoot(Vector3 position, Quaternion rotation, NetworkPlayer player) {
BulletScript bullet = (BulletScript)Instantiate(bulletPrefab, position, rotation);
bullet.Player = player;
burstGunSound.Play();
}
[RPC]
void ShootHoming(Vector3 position, Quaternion rotation, NetworkPlayer player, NetworkPlayer target, Vector3 lastKnownPosition, float homing, bool doSound) {
BulletScript bullet = (BulletScript)Instantiate(bulletPrefab, position, rotation);
bullet.Player = player;
PlayerScript targetScript;
try {
targetScript = PlayerRegistry.All()
.Select(x => x.Value.Player)
.Where(x => x.owner == target)
.OrderBy(x => Vector3.Distance(x.transform.position, lastKnownPosition))
.FirstOrDefault();
} catch (Exception) {
targetScript = null;
}
bullet.target = targetScript == null ? null : targetScript.transform;
bullet.homing = homing;
bullet.speed *= ShotgunBulletSpeedMultiplier;
bullet.recoil = 1;
if (doSound) {
pepperGunSound.Play();
}
}
}
| |
// 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.Composition;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression
{
[ExportSuppressionFixProvider(PredefinedCodeFixProviderNames.Suppression, LanguageNames.CSharp), Shared]
internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider
{
protected override Task<SyntaxTriviaList> CreatePragmaRestoreDirectiveTriviaAsync(Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword);
return CreatePragmaDirectiveTriviaAsync(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
protected override Task<SyntaxTriviaList> CreatePragmaDisableDirectiveTriviaAsync(
Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword);
return CreatePragmaDirectiveTriviaAsync(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
private async Task<SyntaxTriviaList> CreatePragmaDirectiveTriviaAsync(
SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var id = SyntaxFactory.IdentifierName(diagnostic.Id);
var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)await formatNode(pragmaDirective).ConfigureAwait(false);
var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective);
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
if (!string.IsNullOrWhiteSpace(title))
{
var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
triviaList = triviaList.Add(titleComment);
}
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Insert(0, endOfLineTrivia);
}
if (needsTrailingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return triviaList;
}
protected override string DefaultFileExtension
{
get
{
return ".cs";
}
}
protected override string SingleLineCommentStart
{
get
{
return "//";
}
}
protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node)
{
var attributeList = node as AttributeListSyntax;
return attributeList != null &&
attributeList.Target != null &&
attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword;
}
protected override bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia;
}
protected override bool IsEndOfFileToken(SyntaxToken token)
{
return token.Kind() == SyntaxKind.EndOfFileToken;
}
protected override async Task<SyntaxNode> AddGlobalSuppressMessageAttributeAsync(SyntaxNode newRoot, ISymbol targetSymbol, Diagnostic diagnostic, Workspace workspace, CancellationToken cancellationToken)
{
var compilationRoot = (CompilationUnitSyntax)newRoot;
var isFirst = !compilationRoot.AttributeLists.Any();
var leadingTriviaForAttributeList = isFirst && !compilationRoot.HasLeadingTrivia ?
SyntaxFactory.TriviaList(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)) :
default(SyntaxTriviaList);
var attributeList = CreateAttributeList(targetSymbol, diagnostic, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: !isFirst);
attributeList = (AttributeListSyntax)await Formatter.FormatAsync(attributeList, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationRoot.AddAttributeLists(attributeList);
}
private AttributeListSyntax CreateAttributeList(
ISymbol targetSymbol,
Diagnostic diagnostic,
SyntaxTriviaList leadingTrivia,
bool needsLeadingEndOfLine)
{
var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic);
var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(SuppressMessageAttributeName), attributeArguments);
var attributes = new SeparatedSyntaxList<AttributeSyntax>().Add(attribute);
var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
var attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList();
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList));
}
private AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic)
{
// SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target))
var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category));
var categoryArgument = SyntaxFactory.AttributeArgument(category);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title);
var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText));
var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId);
var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.SuppressionPendingJustification));
var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr);
var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument);
var scopeString = GetScopeString(targetSymbol.Kind);
if (scopeString != null)
{
var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString));
var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr);
var targetString = GetTargetString(targetSymbol);
var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString));
var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr);
attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument);
}
return attributeArgumentList;
}
protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute)
{
var attributeSyntax = attribute as AttributeSyntax;
if (attributeSyntax != null)
{
var attributeList = attributeSyntax.Parent as AttributeListSyntax;
return attributeList != null && attributeList.Attributes.Count == 1;
}
return false;
}
protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds)
{
if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword;
hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1;
return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id);
}
enableDirective = false;
hasMultipleIds = false;
return false;
}
protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
var currentKeyword = pragmaWarning.DisableOrRestoreKeyword;
var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword;
var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia);
var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken);
return SyntaxFactory.Trivia(newPragmaWarning);
}
}
}
| |
/******************************************************************************
* 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.Utilclass.SchemaTokenCreator.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.LDAP.VQ.Utilclass
{
public class SchemaTokenCreator
{
private string basestring;
private bool cppcomments = false; // C++ style comments enabled
private bool ccomments = false; // C style comments enabled
private bool iseolsig = false;
private bool cidtolower;
private bool pushedback;
private int peekchar;
private sbyte[] ctype;
private int linenumber = 1;
private int ichar = 1;
private char[] buf;
private System.IO.StreamReader reader = null;
private System.IO.StringReader sreader = null;
private System.IO.Stream input = null;
public string StringValue;
public double NumberValue;
public int lastttype;
private void Initialise()
{
ctype = new sbyte[256];
buf = new char[20];
peekchar = Int32.MaxValue;
WordCharacters('a', 'z');
WordCharacters('A', 'Z');
WordCharacters(128 + 32, 255);
WhitespaceCharacters(0, ' ');
CommentCharacter('/');
QuoteCharacter('"');
QuoteCharacter('\'');
parseNumbers();
}
public SchemaTokenCreator(System.IO.Stream instream)
{
Initialise();
if (instream == null)
{
throw new NullReferenceException();
}
input = instream;
}
public SchemaTokenCreator(System.IO.StreamReader r)
{
Initialise();
if (r == null)
{
throw new NullReferenceException();
}
reader = r;
}
public SchemaTokenCreator(System.IO.StringReader r)
{
Initialise();
if (r == null)
{
throw new NullReferenceException();
}
sreader = r;
}
public void pushBack()
{
pushedback = true;
}
public int CurrentLine
{
get
{
return linenumber;
}
}
public string ToStringValue()
{
string strval;
switch (lastttype)
{
case (int)TokenTypes.EOF:
strval = "EOF";
break;
case (int)TokenTypes.EOL:
strval = "EOL";
break;
case (int)TokenTypes.WORD:
strval = StringValue;
break;
case (int)TokenTypes.STRING:
strval = StringValue;
break;
case (int)TokenTypes.NUMBER:
case (int)TokenTypes.REAL:
strval = "n=" + NumberValue;
break;
default:
{
if (lastttype < 256 && ((ctype[lastttype] & (sbyte)CharacterTypes.STRINGQUOTE) != 0))
{
strval = StringValue;
break;
}
char[] s = new char[3];
s[0] = s[2] = '\'';
s[1] = (char)lastttype;
strval = new string(s);
break;
}
}
return strval;
}
public void WordCharacters(int min, int max)
{
if (min < 0)
min = 0;
if (max >= ctype.Length)
max = ctype.Length - 1;
while (min <= max)
ctype[min++] |= (sbyte)CharacterTypes.ALPHABETIC;
}
public void WhitespaceCharacters(int min, int max)
{
if (min < 0)
min = 0;
if (max >= ctype.Length)
max = ctype.Length - 1;
while (min <= max)
ctype[min++] = (sbyte)CharacterTypes.WHITESPACE;
}
public void OrdinaryCharacters(int min, int max)
{
if (min < 0)
min = 0;
if (max >= ctype.Length)
max = ctype.Length - 1;
while (min <= max)
ctype[min++] = 0;
}
public void OrdinaryCharacter(int ch)
{
if (ch >= 0 && ch < ctype.Length)
ctype[ch] = 0;
}
public void CommentCharacter(int ch)
{
if (ch >= 0 && ch < ctype.Length)
ctype[ch] = (sbyte)CharacterTypes.COMMENTCHAR;
}
public void InitTable()
{
for (int i = ctype.Length; --i >= 0;)
ctype[i] = 0;
}
public void QuoteCharacter(int ch)
{
if (ch >= 0 && ch < ctype.Length)
ctype[ch] = (sbyte)CharacterTypes.STRINGQUOTE;
}
public void parseNumbers()
{
for (int i = '0'; i <= '9'; i++)
ctype[i] |= (sbyte)CharacterTypes.NUMERIC;
ctype['.'] |= (sbyte)CharacterTypes.NUMERIC;
ctype['-'] |= (sbyte)CharacterTypes.NUMERIC;
}
private int read()
{
if (sreader != null)
{
return sreader.Read();
}
else if (reader != null)
{
return reader.Read();
}
else if (input != null)
return input.ReadByte();
else
throw new Exception();
}
public int nextToken()
{
if (pushedback)
{
pushedback = false;
return lastttype;
}
StringValue = null;
int curc = peekchar;
if (curc < 0)
curc = Int32.MaxValue;
if (curc == (Int32.MaxValue - 1))
{
curc = read();
if (curc < 0)
return lastttype = (int)TokenTypes.EOF;
if (curc == '\n')
curc = Int32.MaxValue;
}
if (curc == Int32.MaxValue)
{
curc = read();
if (curc < 0)
return lastttype = (int)TokenTypes.EOF;
}
lastttype = curc;
peekchar = Int32.MaxValue;
int ctype = curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC;
while ((ctype & (sbyte)CharacterTypes.WHITESPACE) != 0)
{
if (curc == '\r')
{
linenumber++;
if (iseolsig)
{
peekchar = (Int32.MaxValue - 1);
return lastttype = (int)TokenTypes.EOL;
}
curc = read();
if (curc == '\n')
curc = read();
}
else
{
if (curc == '\n')
{
linenumber++;
if (iseolsig)
{
return lastttype = (int)TokenTypes.EOL;
}
}
curc = read();
}
if (curc < 0)
return lastttype = (int)TokenTypes.EOF;
ctype = curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC;
}
if ((ctype & (sbyte)CharacterTypes.NUMERIC) != 0)
{
bool checkb = false;
if (curc == '-')
{
curc = read();
if (curc != '.' && (curc < '0' || curc > '9'))
{
peekchar = curc;
return lastttype = '-';
}
checkb = true;
}
double dvar = 0;
int tempvar = 0;
int checkdec = 0;
while (true)
{
if (curc == '.' && checkdec == 0)
checkdec = 1;
else if ('0' <= curc && curc <= '9')
{
dvar = dvar * 10 + (curc - '0');
tempvar += checkdec;
}
else
break;
curc = read();
}
peekchar = curc;
if (tempvar != 0)
{
double divby = 10;
tempvar--;
while (tempvar > 0)
{
divby *= 10;
tempvar--;
}
dvar = dvar / divby;
}
NumberValue = checkb ? -dvar : dvar;
return lastttype = (int)TokenTypes.NUMBER;
}
if ((ctype & (sbyte)CharacterTypes.ALPHABETIC) != 0)
{
int i = 0;
do
{
if (i >= buf.Length)
{
char[] nb = new char[buf.Length * 2];
Array.Copy((Array)buf, 0, (Array)nb, 0, buf.Length);
buf = nb;
}
buf[i++] = (char)curc;
curc = read();
ctype = curc < 0 ? (sbyte)CharacterTypes.WHITESPACE : curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC;
}
while ((ctype & ((sbyte)CharacterTypes.ALPHABETIC | (sbyte)CharacterTypes.NUMERIC)) != 0);
peekchar = curc;
StringValue = new string(buf, 0, i);
if (cidtolower)
StringValue = StringValue.ToLower();
return lastttype = (int)TokenTypes.WORD;
}
if ((ctype & (sbyte)CharacterTypes.STRINGQUOTE) != 0)
{
lastttype = curc;
int i = 0;
int rc = read();
while (rc >= 0 && rc != lastttype && rc != '\n' && rc != '\r')
{
if (rc == '\\')
{
curc = read();
int first = curc;
if (curc >= '0' && curc <= '7')
{
curc = curc - '0';
int loopchar = read();
if ('0' <= loopchar && loopchar <= '7')
{
curc = (curc << 3) + (loopchar - '0');
loopchar = read();
if ('0' <= loopchar && loopchar <= '7' && first <= '3')
{
curc = (curc << 3) + (loopchar - '0');
rc = read();
}
else
rc = loopchar;
}
else
rc = loopchar;
}
else
{
switch (curc)
{
case 'f':
curc = 0xC;
break;
case 'a':
curc = 0x7;
break;
case 'b':
curc = '\b';
break;
case 'v':
curc = 0xB;
break;
case 'n':
curc = '\n';
break;
case 'r':
curc = '\r';
break;
case 't':
curc = '\t';
break;
default:
break;
}
rc = read();
}
}
else
{
curc = rc;
rc = read();
}
if (i >= buf.Length)
{
char[] nb = new char[buf.Length * 2];
Array.Copy((Array)buf, 0, (Array)nb, 0, buf.Length);
buf = nb;
}
buf[i++] = (char)curc;
}
peekchar = (rc == lastttype) ? Int32.MaxValue : rc;
StringValue = new string(buf, 0, i);
return lastttype;
}
if (curc == '/' && (cppcomments || ccomments))
{
curc = read();
if (curc == '*' && ccomments)
{
int prevc = 0;
while ((curc = read()) != '/' || prevc != '*')
{
if (curc == '\r')
{
linenumber++;
curc = read();
if (curc == '\n')
{
curc = read();
}
}
else
{
if (curc == '\n')
{
linenumber++;
curc = read();
}
}
if (curc < 0)
return lastttype = (int)TokenTypes.EOF;
prevc = curc;
}
return nextToken();
}
else if (curc == '/' && cppcomments)
{
while ((curc = read()) != '\n' && curc != '\r' && curc >= 0)
;
peekchar = curc;
return nextToken();
}
else
{
if ((this.ctype['/'] & (sbyte)CharacterTypes.COMMENTCHAR) != 0)
{
while ((curc = read()) != '\n' && curc != '\r' && curc >= 0)
;
peekchar = curc;
return nextToken();
}
else
{
peekchar = curc;
return lastttype = '/';
}
}
}
if ((ctype & (sbyte)CharacterTypes.COMMENTCHAR) != 0)
{
while ((curc = read()) != '\n' && curc != '\r' && curc >= 0)
;
peekchar = curc;
return nextToken();
}
return lastttype = curc;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/reservation_note_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Booking.RPC {
public static partial class ReservationNoteSvc
{
static readonly string __ServiceName = "holms.types.booking.rpc.ReservationNoteSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest> __Marshaller_ReservationNoteFulfillmentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> __Marshaller_ReservationIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse> __Marshaller_ReservationNoteSvcGetNotesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Reservations.ReservationNote> __Marshaller_ReservationNote = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Reservations.ReservationNote.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator> __Marshaller_ReservationNoteIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SetNoteFulfillment = new grpc::Method<global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"SetNoteFulfillment",
__Marshaller_ReservationNoteFulfillmentRequest,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse> __Method_GetReservationNotes = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetReservationNotes",
__Marshaller_ReservationIndicator,
__Marshaller_ReservationNoteSvcGetNotesResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Reservations.ReservationNote, global::Google.Protobuf.WellKnownTypes.Empty> __Method_AddReservationNote = new grpc::Method<global::HOLMS.Types.Booking.Reservations.ReservationNote, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"AddReservationNote",
__Marshaller_ReservationNote,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Booking.Reservations.ReservationNote, global::Google.Protobuf.WellKnownTypes.Empty> __Method_UpdateReservationNote = new grpc::Method<global::HOLMS.Types.Booking.Reservations.ReservationNote, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"UpdateReservationNote",
__Marshaller_ReservationNote,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator, global::Google.Protobuf.WellKnownTypes.Empty> __Method_RemoveReservationNote = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"RemoveReservationNote",
__Marshaller_ReservationNoteIndicator,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Booking.RPC.ReservationNoteSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ReservationNoteSvc</summary>
public abstract partial class ReservationNoteSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SetNoteFulfillment(global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse> GetReservationNotes(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> AddReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> UpdateReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> RemoveReservationNote(global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ReservationNoteSvc</summary>
public partial class ReservationNoteSvcClient : grpc::ClientBase<ReservationNoteSvcClient>
{
/// <summary>Creates a new client for ReservationNoteSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ReservationNoteSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ReservationNoteSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ReservationNoteSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ReservationNoteSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ReservationNoteSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty SetNoteFulfillment(global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetNoteFulfillment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty SetNoteFulfillment(global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SetNoteFulfillment, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SetNoteFulfillmentAsync(global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetNoteFulfillmentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SetNoteFulfillmentAsync(global::HOLMS.Types.Booking.RPC.ReservationNoteFulfillmentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SetNoteFulfillment, null, options, request);
}
public virtual global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse GetReservationNotes(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationNotes(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse GetReservationNotes(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetReservationNotes, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse> GetReservationNotesAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationNotesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.ReservationNoteSvcGetNotesResponse> GetReservationNotesAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetReservationNotes, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty AddReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddReservationNote(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty AddReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AddReservationNote, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> AddReservationNoteAsync(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddReservationNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> AddReservationNoteAsync(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AddReservationNote, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty UpdateReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateReservationNote(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty UpdateReservationNote(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UpdateReservationNote, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpdateReservationNoteAsync(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateReservationNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpdateReservationNoteAsync(global::HOLMS.Types.Booking.Reservations.ReservationNote request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UpdateReservationNote, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty RemoveReservationNote(global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RemoveReservationNote(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty RemoveReservationNote(global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_RemoveReservationNote, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> RemoveReservationNoteAsync(global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RemoveReservationNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> RemoveReservationNoteAsync(global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_RemoveReservationNote, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ReservationNoteSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new ReservationNoteSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ReservationNoteSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SetNoteFulfillment, serviceImpl.SetNoteFulfillment)
.AddMethod(__Method_GetReservationNotes, serviceImpl.GetReservationNotes)
.AddMethod(__Method_AddReservationNote, serviceImpl.AddReservationNote)
.AddMethod(__Method_UpdateReservationNote, serviceImpl.UpdateReservationNote)
.AddMethod(__Method_RemoveReservationNote, serviceImpl.RemoveReservationNote).Build();
}
}
}
#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.Threading;
using System.Threading.Tasks;
namespace System.Runtime
{
internal sealed class InputQueue<T> : IDisposable where T : class
{
private static Action<object> s_completeOutstandingReadersCallback;
private static Action<object> s_completeWaitersFalseCallback;
private static Action<object> s_completeWaitersTrueCallback;
private static Action<object> s_onDispatchCallback;
private static Action<object> s_onInvokeDequeuedCallback;
private QueueState _queueState;
private ItemQueue _itemQueue;
private Queue<IQueueReader> _readerQueue;
private List<IQueueWaiter> _waiterList;
public InputQueue()
{
_itemQueue = new ItemQueue();
_readerQueue = new Queue<IQueueReader>();
_waiterList = new List<IQueueWaiter>();
_queueState = QueueState.Open;
}
public InputQueue(Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator)
: this()
{
Fx.Assert(asyncCallbackGenerator != null, "use default ctor if you don't have a generator");
AsyncCallbackGenerator = asyncCallbackGenerator;
}
public int PendingCount
{
get
{
lock (ThisLock)
{
return _itemQueue.ItemCount;
}
}
}
// Users like ServiceModel can hook this abort ICommunicationObject or handle other non-IDisposable objects
public Action<T> DisposeItemCallback
{
get;
set;
}
// Users like ServiceModel can hook this to wrap the AsyncQueueReader callback functionality for tracing, etc
private Func<Action<AsyncCallback, IAsyncResult>> AsyncCallbackGenerator
{
get;
set;
}
private object ThisLock
{
get { return _itemQueue; }
}
public IAsyncResult BeginDequeue(TimeSpan timeout, AsyncCallback callback, object state)
{
Item item = default(Item);
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else
{
AsyncQueueReader reader = new AsyncQueueReader(this, timeout, callback, state);
_readerQueue.Enqueue(reader);
return reader;
}
}
else if (_queueState == QueueState.Shutdown)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else if (_itemQueue.HasAnyItem)
{
AsyncQueueReader reader = new AsyncQueueReader(this, timeout, callback, state);
_readerQueue.Enqueue(reader);
return reader;
}
}
}
InvokeDequeuedCallback(item.DequeuedCallback);
return new CompletedAsyncResult<T>(item.GetValue(), callback, state);
}
public IAsyncResult BeginWaitForItem(TimeSpan timeout, AsyncCallback callback, object state)
{
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (!_itemQueue.HasAvailableItem)
{
AsyncQueueWaiter waiter = new AsyncQueueWaiter(timeout, callback, state);
_waiterList.Add(waiter);
return waiter;
}
}
else if (_queueState == QueueState.Shutdown)
{
if (!_itemQueue.HasAvailableItem && _itemQueue.HasAnyItem)
{
AsyncQueueWaiter waiter = new AsyncQueueWaiter(timeout, callback, state);
_waiterList.Add(waiter);
return waiter;
}
}
}
return new CompletedAsyncResult<bool>(true, callback, state);
}
public void Close()
{
Dispose();
}
public T Dequeue(TimeSpan timeout)
{
T value;
if (!Dequeue(timeout, out value))
{
throw Fx.Exception.AsError(new TimeoutException(InternalSR.TimeoutInputQueueDequeue(timeout)));
}
return value;
}
public async Task<T> DequeueAsync(TimeSpan timeout)
{
(bool success, T value) = await TryDequeueAsync(timeout);
if (!success)
{
throw Fx.Exception.AsError(new TimeoutException(InternalSR.TimeoutInputQueueDequeue(timeout)));
}
return value;
}
public async Task<(bool, T)> TryDequeueAsync(TimeSpan timeout)
{
TaskQueueReader reader = null;
Item item = new Item();
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else
{
reader = new TaskQueueReader(this);
_readerQueue.Enqueue(reader);
}
}
else if (_queueState == QueueState.Shutdown)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else if (_itemQueue.HasAnyItem)
{
reader = new TaskQueueReader(this);
_readerQueue.Enqueue(reader);
}
else
{
return (true, default(T));
}
}
else // queueState == QueueState.Closed
{
return (true, default(T));
}
}
if (reader != null)
{
return await reader.WaitAsync(timeout);
}
else
{
InvokeDequeuedCallback(item.DequeuedCallback);
return (true, item.GetValue());
}
}
public bool Dequeue(TimeSpan timeout, out T value)
{
WaitQueueReader reader = null;
Item item = new Item();
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else
{
reader = new WaitQueueReader(this);
_readerQueue.Enqueue(reader);
}
}
else if (_queueState == QueueState.Shutdown)
{
if (_itemQueue.HasAvailableItem)
{
item = _itemQueue.DequeueAvailableItem();
}
else if (_itemQueue.HasAnyItem)
{
reader = new WaitQueueReader(this);
_readerQueue.Enqueue(reader);
}
else
{
value = default(T);
return true;
}
}
else // queueState == QueueState.Closed
{
value = default(T);
return true;
}
}
if (reader != null)
{
return reader.Wait(timeout, out value);
}
else
{
InvokeDequeuedCallback(item.DequeuedCallback);
value = item.GetValue();
return true;
}
}
public void Dispatch()
{
IQueueReader reader = null;
Item item = new Item();
IQueueReader[] outstandingReaders = null;
IQueueWaiter[] waiters = null;
bool itemAvailable = true;
lock (ThisLock)
{
itemAvailable = !((_queueState == QueueState.Closed) || (_queueState == QueueState.Shutdown));
GetWaiters(out waiters);
if (_queueState != QueueState.Closed)
{
_itemQueue.MakePendingItemAvailable();
if (_readerQueue.Count > 0)
{
item = _itemQueue.DequeueAvailableItem();
reader = _readerQueue.Dequeue();
if (_queueState == QueueState.Shutdown && _readerQueue.Count > 0 && _itemQueue.ItemCount == 0)
{
outstandingReaders = new IQueueReader[_readerQueue.Count];
_readerQueue.CopyTo(outstandingReaders, 0);
_readerQueue.Clear();
itemAvailable = false;
}
}
}
}
if (outstandingReaders != null)
{
if (s_completeOutstandingReadersCallback == null)
{
s_completeOutstandingReadersCallback = new Action<object>(CompleteOutstandingReadersCallback);
}
ActionItem.Schedule(s_completeOutstandingReadersCallback, outstandingReaders);
}
if (waiters != null)
{
CompleteWaitersLater(itemAvailable, waiters);
}
if (reader != null)
{
InvokeDequeuedCallback(item.DequeuedCallback);
reader.Set(item);
}
}
public bool EndDequeue(IAsyncResult result, out T value)
{
CompletedAsyncResult<T> typedResult = result as CompletedAsyncResult<T>;
if (typedResult != null)
{
value = CompletedAsyncResult<T>.End(result);
return true;
}
return AsyncQueueReader.End(result, out value);
}
public T EndDequeue(IAsyncResult result)
{
T value;
if (!EndDequeue(result, out value))
{
throw Fx.Exception.AsError(new TimeoutException());
}
return value;
}
public bool EndWaitForItem(IAsyncResult result)
{
CompletedAsyncResult<bool> typedResult = result as CompletedAsyncResult<bool>;
if (typedResult != null)
{
return CompletedAsyncResult<bool>.End(result);
}
return AsyncQueueWaiter.End(result);
}
public void EnqueueAndDispatch(T item)
{
EnqueueAndDispatch(item, null);
}
// dequeuedCallback is called as an item is dequeued from the InputQueue. The
// InputQueue lock is not held during the callback. However, the user code will
// not be notified of the item being available until the callback returns. If you
// are not sure if the callback will block for a long time, then first call
// IOThreadScheduler.ScheduleCallback to get to a "safe" thread.
public void EnqueueAndDispatch(T item, Action dequeuedCallback)
{
EnqueueAndDispatch(item, dequeuedCallback, true);
}
public void EnqueueAndDispatch(Exception exception, Action dequeuedCallback, bool canDispatchOnThisThread)
{
Fx.Assert(exception != null, "EnqueueAndDispatch: exception parameter should not be null");
EnqueueAndDispatch(new Item(exception, dequeuedCallback), canDispatchOnThisThread);
}
public void EnqueueAndDispatch(T item, Action dequeuedCallback, bool canDispatchOnThisThread)
{
Fx.Assert(item != null, "EnqueueAndDispatch: item parameter should not be null");
EnqueueAndDispatch(new Item(item, dequeuedCallback), canDispatchOnThisThread);
}
public bool EnqueueWithoutDispatch(T item, Action dequeuedCallback)
{
Fx.Assert(item != null, "EnqueueWithoutDispatch: item parameter should not be null");
return EnqueueWithoutDispatch(new Item(item, dequeuedCallback));
}
public bool EnqueueWithoutDispatch(Exception exception, Action dequeuedCallback)
{
Fx.Assert(exception != null, "EnqueueWithoutDispatch: exception parameter should not be null");
return EnqueueWithoutDispatch(new Item(exception, dequeuedCallback));
}
public void Shutdown()
{
Shutdown(null);
}
// Don't let any more items in. Differs from Close in that we keep around
// existing items in our itemQueue for possible future calls to Dequeue
public void Shutdown(Func<Exception> pendingExceptionGenerator)
{
IQueueReader[] outstandingReaders = null;
lock (ThisLock)
{
if (_queueState == QueueState.Shutdown)
{
return;
}
if (_queueState == QueueState.Closed)
{
return;
}
_queueState = QueueState.Shutdown;
if (_readerQueue.Count > 0 && _itemQueue.ItemCount == 0)
{
outstandingReaders = new IQueueReader[_readerQueue.Count];
_readerQueue.CopyTo(outstandingReaders, 0);
_readerQueue.Clear();
}
}
if (outstandingReaders != null)
{
for (int i = 0; i < outstandingReaders.Length; i++)
{
Exception exception = (pendingExceptionGenerator != null) ? pendingExceptionGenerator() : null;
outstandingReaders[i].Set(new Item(exception, null));
}
}
}
public bool WaitForItem(TimeSpan timeout)
{
WaitQueueWaiter waiter = null;
bool itemAvailable = false;
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (_itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else
{
waiter = new WaitQueueWaiter();
_waiterList.Add(waiter);
}
}
else if (_queueState == QueueState.Shutdown)
{
if (_itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else if (_itemQueue.HasAnyItem)
{
waiter = new WaitQueueWaiter();
_waiterList.Add(waiter);
}
else
{
return true;
}
}
else // queueState == QueueState.Closed
{
return true;
}
}
if (waiter != null)
{
return waiter.Wait(timeout);
}
else
{
return itemAvailable;
}
}
public Task<bool> WaitForItemAsync(TimeSpan timeout)
{
TaskQueueWaiter waiter = null;
bool itemAvailable = false;
lock (ThisLock)
{
if (_queueState == QueueState.Open)
{
if (_itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else
{
waiter = new TaskQueueWaiter();
_waiterList.Add(waiter);
}
}
else if (_queueState == QueueState.Shutdown)
{
if (_itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else if (_itemQueue.HasAnyItem)
{
waiter = new TaskQueueWaiter();
_waiterList.Add(waiter);
}
else
{
return Task.FromResult(true);
}
}
else // queueState == QueueState.Closed
{
return Task.FromResult(true);
}
}
if (waiter != null)
{
return waiter.WaitAsync(timeout);
}
else
{
return Task.FromResult(itemAvailable);
}
}
public void Dispose()
{
bool dispose = false;
lock (ThisLock)
{
if (_queueState != QueueState.Closed)
{
_queueState = QueueState.Closed;
dispose = true;
}
}
if (dispose)
{
while (_readerQueue.Count > 0)
{
IQueueReader reader = _readerQueue.Dequeue();
reader.Set(default(Item));
}
while (_itemQueue.HasAnyItem)
{
Item item = _itemQueue.DequeueAnyItem();
DisposeItem(item);
InvokeDequeuedCallback(item.DequeuedCallback);
}
}
}
private void DisposeItem(Item item)
{
T value = item.Value;
if (value != null)
{
if (value is IDisposable)
{
((IDisposable)value).Dispose();
}
else
{
Action<T> disposeItemCallback = DisposeItemCallback;
if (disposeItemCallback != null)
{
disposeItemCallback(value);
}
}
}
}
private static void CompleteOutstandingReadersCallback(object state)
{
IQueueReader[] outstandingReaders = (IQueueReader[])state;
for (int i = 0; i < outstandingReaders.Length; i++)
{
outstandingReaders[i].Set(default(Item));
}
}
private static void CompleteWaiters(bool itemAvailable, IQueueWaiter[] waiters)
{
for (int i = 0; i < waiters.Length; i++)
{
waiters[i].Set(itemAvailable);
}
}
private static void CompleteWaitersFalseCallback(object state)
{
CompleteWaiters(false, (IQueueWaiter[])state);
}
private static void CompleteWaitersLater(bool itemAvailable, IQueueWaiter[] waiters)
{
if (itemAvailable)
{
if (s_completeWaitersTrueCallback == null)
{
s_completeWaitersTrueCallback = new Action<object>(CompleteWaitersTrueCallback);
}
ActionItem.Schedule(s_completeWaitersTrueCallback, waiters);
}
else
{
if (s_completeWaitersFalseCallback == null)
{
s_completeWaitersFalseCallback = new Action<object>(CompleteWaitersFalseCallback);
}
ActionItem.Schedule(s_completeWaitersFalseCallback, waiters);
}
}
private static void CompleteWaitersTrueCallback(object state)
{
CompleteWaiters(true, (IQueueWaiter[])state);
}
private static void InvokeDequeuedCallback(Action dequeuedCallback)
{
if (dequeuedCallback != null)
{
dequeuedCallback();
}
}
private static void InvokeDequeuedCallbackLater(Action dequeuedCallback)
{
if (dequeuedCallback != null)
{
if (s_onInvokeDequeuedCallback == null)
{
s_onInvokeDequeuedCallback = new Action<object>(OnInvokeDequeuedCallback);
}
ActionItem.Schedule(s_onInvokeDequeuedCallback, dequeuedCallback);
}
}
private static void OnDispatchCallback(object state)
{
((InputQueue<T>)state).Dispatch();
}
private static void OnInvokeDequeuedCallback(object state)
{
Fx.Assert(state != null, "InputQueue.OnInvokeDequeuedCallback: (state != null)");
Action dequeuedCallback = (Action)state;
dequeuedCallback();
}
private void EnqueueAndDispatch(Item item, bool canDispatchOnThisThread)
{
bool disposeItem = false;
IQueueReader reader = null;
bool dispatchLater = false;
IQueueWaiter[] waiters = null;
bool itemAvailable = true;
lock (ThisLock)
{
itemAvailable = !((_queueState == QueueState.Closed) || (_queueState == QueueState.Shutdown));
GetWaiters(out waiters);
if (_queueState == QueueState.Open)
{
if (canDispatchOnThisThread)
{
if (_readerQueue.Count == 0)
{
_itemQueue.EnqueueAvailableItem(item);
}
else
{
reader = _readerQueue.Dequeue();
}
}
else
{
if (_readerQueue.Count == 0)
{
_itemQueue.EnqueueAvailableItem(item);
}
else
{
_itemQueue.EnqueuePendingItem(item);
dispatchLater = true;
}
}
}
else // queueState == QueueState.Closed || queueState == QueueState.Shutdown
{
disposeItem = true;
}
}
if (waiters != null)
{
if (canDispatchOnThisThread)
{
CompleteWaiters(itemAvailable, waiters);
}
else
{
CompleteWaitersLater(itemAvailable, waiters);
}
}
if (reader != null)
{
InvokeDequeuedCallback(item.DequeuedCallback);
reader.Set(item);
}
if (dispatchLater)
{
if (s_onDispatchCallback == null)
{
s_onDispatchCallback = new Action<object>(OnDispatchCallback);
}
ActionItem.Schedule(s_onDispatchCallback, this);
}
else if (disposeItem)
{
InvokeDequeuedCallback(item.DequeuedCallback);
DisposeItem(item);
}
}
// This will not block, however, Dispatch() must be called later if this function
// returns true.
private bool EnqueueWithoutDispatch(Item item)
{
lock (ThisLock)
{
// Open
if (_queueState != QueueState.Closed && _queueState != QueueState.Shutdown)
{
if (_readerQueue.Count == 0 && _waiterList.Count == 0)
{
_itemQueue.EnqueueAvailableItem(item);
return false;
}
else
{
_itemQueue.EnqueuePendingItem(item);
return true;
}
}
}
DisposeItem(item);
InvokeDequeuedCallbackLater(item.DequeuedCallback);
return false;
}
private void GetWaiters(out IQueueWaiter[] waiters)
{
if (_waiterList.Count > 0)
{
waiters = _waiterList.ToArray();
_waiterList.Clear();
}
else
{
waiters = null;
}
}
// Used for timeouts. The InputQueue must remove readers from its reader queue to prevent
// dispatching items to timed out readers.
private bool RemoveReader(IQueueReader reader)
{
Fx.Assert(reader != null, "InputQueue.RemoveReader: (reader != null)");
lock (ThisLock)
{
if (_queueState == QueueState.Open || _queueState == QueueState.Shutdown)
{
bool removed = false;
for (int i = _readerQueue.Count; i > 0; i--)
{
IQueueReader temp = _readerQueue.Dequeue();
if (object.ReferenceEquals(temp, reader))
{
removed = true;
}
else
{
_readerQueue.Enqueue(temp);
}
}
return removed;
}
}
return false;
}
private enum QueueState
{
Open,
Shutdown,
Closed
}
private interface IQueueReader
{
void Set(Item item);
}
private interface IQueueWaiter
{
void Set(bool itemAvailable);
}
internal struct Item
{
private T _value;
public Item(T value, Action dequeuedCallback)
: this(value, null, dequeuedCallback)
{
}
public Item(Exception exception, Action dequeuedCallback)
: this(null, exception, dequeuedCallback)
{
}
private Item(T value, Exception exception, Action dequeuedCallback)
{
_value = value;
Exception = exception;
DequeuedCallback = dequeuedCallback;
}
public Action DequeuedCallback { get; }
public Exception Exception { get; }
public T Value
{
get { return _value; }
}
public T GetValue()
{
if (Exception != null)
{
throw Fx.Exception.AsError(Exception);
}
return _value;
}
}
internal class AsyncQueueReader : AsyncResult, IQueueReader
{
private static Action<object> s_timerCallback = new Action<object>(AsyncQueueReader.TimerCallback);
private bool _expired;
private InputQueue<T> _inputQueue;
private T _item;
private Timer _timer;
public AsyncQueueReader(InputQueue<T> inputQueue, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
if (inputQueue.AsyncCallbackGenerator != null)
{
base.VirtualCallback = inputQueue.AsyncCallbackGenerator();
}
_inputQueue = inputQueue;
if (timeout != TimeSpan.MaxValue)
{
_timer = new Timer(new TimerCallback(s_timerCallback), this, timeout, TimeSpan.FromMilliseconds(-1));
}
}
public static bool End(IAsyncResult result, out T value)
{
AsyncQueueReader readerResult = AsyncResult.End<AsyncQueueReader>(result);
if (readerResult._expired)
{
value = default(T);
return false;
}
else
{
value = readerResult._item;
return true;
}
}
public void Set(Item item)
{
_item = item.Value;
if (_timer != null)
{
_timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
}
Complete(false, item.Exception);
}
private static void TimerCallback(object state)
{
AsyncQueueReader thisPtr = (AsyncQueueReader)state;
if (thisPtr._inputQueue.RemoveReader(thisPtr))
{
thisPtr._expired = true;
thisPtr.Complete(false);
}
}
}
internal class AsyncQueueWaiter : AsyncResult, IQueueWaiter
{
private static Action<object> s_timerCallback = new Action<object>(AsyncQueueWaiter.TimerCallback);
private bool _itemAvailable;
private Timer _timer;
public AsyncQueueWaiter(TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
{
if (timeout != TimeSpan.MaxValue)
{
_timer = new Timer(new TimerCallback(s_timerCallback), this, timeout, TimeSpan.FromMilliseconds(-1));
}
}
private object ThisLock { get; } = new object();
public static bool End(IAsyncResult result)
{
AsyncQueueWaiter waiterResult = AsyncResult.End<AsyncQueueWaiter>(result);
return waiterResult._itemAvailable;
}
public void Set(bool itemAvailable)
{
bool timely;
lock (ThisLock)
{
timely = (_timer == null) || _timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
_itemAvailable = itemAvailable;
}
if (timely)
{
Complete(false);
}
}
private static void TimerCallback(object state)
{
AsyncQueueWaiter thisPtr = (AsyncQueueWaiter)state;
thisPtr.Complete(false);
}
}
internal class ItemQueue
{
private int _head;
private Item[] _items;
private int _pendingCount;
public ItemQueue()
{
_items = new Item[1];
}
public bool HasAnyItem
{
get { return ItemCount > 0; }
}
public bool HasAvailableItem
{
get { return ItemCount > _pendingCount; }
}
public int ItemCount { get; private set; }
public Item DequeueAnyItem()
{
if (_pendingCount == ItemCount)
{
_pendingCount--;
}
return DequeueItemCore();
}
public Item DequeueAvailableItem()
{
Fx.AssertAndThrow(ItemCount != _pendingCount, "ItemQueue does not contain any available items");
return DequeueItemCore();
}
public void EnqueueAvailableItem(Item item)
{
EnqueueItemCore(item);
}
public void EnqueuePendingItem(Item item)
{
EnqueueItemCore(item);
_pendingCount++;
}
public void MakePendingItemAvailable()
{
Fx.AssertAndThrow(_pendingCount != 0, "ItemQueue does not contain any pending items");
_pendingCount--;
}
private Item DequeueItemCore()
{
Fx.AssertAndThrow(ItemCount != 0, "ItemQueue does not contain any items");
Item item = _items[_head];
_items[_head] = new Item();
ItemCount--;
_head = (_head + 1) % _items.Length;
return item;
}
private void EnqueueItemCore(Item item)
{
if (ItemCount == _items.Length)
{
Item[] newItems = new Item[_items.Length * 2];
for (int i = 0; i < ItemCount; i++)
{
newItems[i] = _items[(_head + i) % _items.Length];
}
_head = 0;
_items = newItems;
}
int tail = (_head + ItemCount) % _items.Length;
_items[tail] = item;
ItemCount++;
}
}
internal class WaitQueueReader : IQueueReader
{
private Exception _exception;
private InputQueue<T> _inputQueue;
private T _item;
private ManualResetEvent _waitEvent;
public WaitQueueReader(InputQueue<T> inputQueue)
{
_inputQueue = inputQueue;
_waitEvent = new ManualResetEvent(false);
}
public void Set(Item item)
{
lock (this)
{
Fx.Assert(_item == null, "InputQueue.WaitQueueReader.Set: (this.item == null)");
Fx.Assert(_exception == null, "InputQueue.WaitQueueReader.Set: (this.exception == null)");
_exception = item.Exception;
_item = item.Value;
_waitEvent.Set();
}
}
public bool Wait(TimeSpan timeout, out T value)
{
bool isSafeToClose = false;
try
{
if (!TimeoutHelper.WaitOne(_waitEvent, timeout))
{
if (_inputQueue.RemoveReader(this))
{
value = default(T);
isSafeToClose = true;
return false;
}
else
{
_waitEvent.WaitOne();
}
}
isSafeToClose = true;
}
finally
{
if (isSafeToClose)
{
_waitEvent.Dispose();
}
}
if (_exception != null)
{
throw Fx.Exception.AsError(_exception);
}
value = _item;
return true;
}
}
internal class TaskQueueReader : IQueueReader
{
private TaskCompletionSource<T> _tcs = new TaskCompletionSource<T>();
private InputQueue<T> _inputQueue;
public TaskQueueReader(InputQueue<T> inputQueue)
{
_inputQueue = inputQueue;
}
public void Set(Item item)
{
if (item.Exception != null)
{
_tcs.TrySetException(item.Exception);
}
else
{
_tcs.TrySetResult(item.Value);
}
}
public async Task<(bool, T)> WaitAsync(TimeSpan timeout)
{
if (!await _tcs.Task.AwaitWithTimeout(timeout))
{
if (_inputQueue.RemoveReader(this))
{
return (false, default(T));
}
else
{
await _tcs.Task;
}
}
return (true, await _tcs.Task);
}
}
internal class WaitQueueWaiter : IQueueWaiter
{
private bool _itemAvailable;
private ManualResetEvent _waitEvent;
public WaitQueueWaiter()
{
_waitEvent = new ManualResetEvent(false);
}
public void Set(bool itemAvailable)
{
lock (this)
{
_itemAvailable = itemAvailable;
_waitEvent.Set();
}
}
public bool Wait(TimeSpan timeout)
{
if (!TimeoutHelper.WaitOne(_waitEvent, timeout))
{
return false;
}
return _itemAvailable;
}
}
internal class TaskQueueWaiter : IQueueWaiter
{
private TaskCompletionSource<bool> _tcs;
public TaskQueueWaiter()
{
_tcs = new TaskCompletionSource<bool>();
}
public void Set(bool itemAvailable)
{
lock (this)
{
_tcs.TrySetResult(itemAvailable);
}
}
public async Task<bool> WaitAsync(TimeSpan timeout)
{
if (!await _tcs.Task.AwaitWithTimeout(timeout))
{
return false;
}
return await _tcs.Task;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
namespace PythonToolsUITests {
[TestClass]
public class AddImportTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
/// <summary>
/// Imports get added after a doc string
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void DocString() {
string expectedText = @"'''fob'''
import itertools
itertools";
AddSmartTagTest("DocString.py", 3, 10, new[] { "import itertools" }, 0, expectedText);
}
/// <summary>
/// Imports get added after a unicode doc string
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void UnicodeDocString() {
string expectedText = @"u'''fob'''
import itertools
itertools";
AddSmartTagTest("UnicodeDocString.py", 3, 10, new[] { "import itertools" }, 0, expectedText);
}
/// <summary>
/// Future import gets added after doc string, but before other imports.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void DocStringFuture() {
string expectedText = @"'''fob'''
from __future__ import with_statement
import itertools
with_statement";
AddSmartTagTest("DocStringFuture.py", 4, 10, new[] { "from __future__ import with_statement" }, 0, expectedText);
}
/// <summary>
/// Add a from .. import for a function in another module
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFrom() {
string expectedText = @"from test_module import module_func
module_func()";
AddSmartTagTest("ImportFunctionFrom.py", 1, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from .. import for a function in a subpackage
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromSubpackage() {
string expectedText = @"from test_package.sub_package import subpackage_method
subpackage_method()";
AddSmartTagTest("ImportFunctionFromSubpackage.py", 1, 1, new[] { "from test_package.sub_package import subpackage_method" }, 0, expectedText);
}
/// <summary>
/// We should understand assignment from import statements even in the face of errors
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportWithErrors() {
// http://pytools.codeplex.com/workitem/547
AddSmartTagTest("ImportWithError.py", 1, 9, _NoSmartTags);
AddSmartTagTest("ImportWithError.py", 2, 3, _NoSmartTags);
}
/// <summary>
/// Add a from .. import for a function in a built-in module
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportBuiltinFunction() {
string expectedText = @"from sys import getrecursionlimit
getrecursionlimit()";
AddSmartTagTest("ImportBuiltinFunction.py", 1, 1, new[] { "from sys import getrecursionlimit" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImport() {
string expectedText = @"from test_module import module_func_2, module_func
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImport.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module and
/// the existing import is an "from ... import oar as baz" import.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImportAsName() {
string expectedText = @"from test_module import module_func_2 as oar, module_func
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImportAsName.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module and
/// the existing import contains parens around the imported items list.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImportParens() {
string expectedText = @"from test_module import (module_func_2, module_func)
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImportParens.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module and
/// the existing import contains parens around the imported items list and the existing import contains an "as" import.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImportParensAsName() {
string expectedText = @"from test_module import (module_func_2 as oar, module_func)
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImportParensAsName.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module and
/// the existing import contains parens around the imported items list and the existing import contains an "as" import
/// and there's a trailing comma at the end.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImportParensAsNameTrailingComma() {
string expectedText = @"from test_module import (module_func_2 as oar, module_func)
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImportParensAsNameTrailingComma.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Add a from ... import for a function in another module when a from import already exists for the same module and
/// the existing import contains parens around the imported items list and there's a trailing comma at the end.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportFunctionFromExistingFromImportParensTrailingComma() {
string expectedText = @"from test_module import (module_func_2, module_func)
module_func()";
AddSmartTagTest("ImportFunctionFromExistingFromImportParensTrailingComma.py", 2, 1, new[] { "from test_module import module_func" }, 0, expectedText);
}
/// <summary>
/// Adds an import statement for a package.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportPackage() {
string expectedText = @"import test_package
test_package";
AddSmartTagTest("ImportPackage.py", 1, 1, new[] { "*", "import test_package" }, 1, expectedText);
}
/// <summary>
/// Adds an import statement for a package.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void ImportSubPackage() {
string expectedText = @"from test_package import sub_package
sub_package";
AddSmartTagTest("ImportSubPackage.py", 1, 1, new[] { "from test_package import sub_package" }, 0, expectedText);
}
private static string[] _NoSmartTags = new string[0];
/// <summary>
/// Adds an import statement for a package.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void Parameters() {
var getreclimit = new[] { "from sys import getrecursionlimit" };
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\AddImport.sln");
var item = project.ProjectItems.Item("Parameters.py");
var window = item.Open();
window.Activate();
var doc = app.GetDocument(item.Document.FullName);
AddSmartTagTest(doc, 1, 19, _NoSmartTags);
AddSmartTagTest(doc, 1, 30, getreclimit);
AddSmartTagTest(doc, 4, 18, _NoSmartTags);
AddSmartTagTest(doc, 7, 18, _NoSmartTags);
AddSmartTagTest(doc, 10, 20, _NoSmartTags);
AddSmartTagTest(doc, 13, 22, _NoSmartTags);
AddSmartTagTest(doc, 16, 22, _NoSmartTags);
AddSmartTagTest(doc, 19, 22, _NoSmartTags);
AddSmartTagTest(doc, 19, 35, getreclimit);
AddSmartTagTest(doc, 22, 25, _NoSmartTags);
AddSmartTagTest(doc, 22, 56, getreclimit);
AddSmartTagTest(doc, 25, 38, _NoSmartTags);
AddSmartTagTest(doc, 25, 38, _NoSmartTags);
AddSmartTagTest(doc, 25, 48, getreclimit);
AddSmartTagTest(doc, 29, 12, _NoSmartTags);
AddSmartTagTest(doc, 29, 42, getreclimit);
AddSmartTagTest(doc, 34, 26, _NoSmartTags);
AddSmartTagTest(doc, 34, 31, getreclimit);
AddSmartTagTest(doc, 42, 16, _NoSmartTags);
AddSmartTagTest(doc, 51, 16, _NoSmartTags);
}
}
/// <summary>
/// Adds an import statement for a package.
/// </summary>
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void AssignedWithoutTypeInfo() {
AddSmartTagTest("Assignments.py", 1, 2, _NoSmartTags);
AddSmartTagTest("Assignments.py", 1, 8, _NoSmartTags);
}
private static void AddSmartTagTest(EditorWindow doc, int line, int column, string[] expectedActions, int invokeAction = -1, string expectedText = null) {
doc.Invoke(() => {
var point = doc.TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1).Start.Add(column - 1);
doc.TextView.Caret.MoveTo(point);
});
if (expectedActions.Length > 0) {
using (var sh = doc.StartSmartTagSession()) {
var actions = sh.Session.Actions.ToList();
if (expectedActions[0] == "*") {
AssertUtil.ContainsAtLeast(
actions.Select(a => a.DisplayText.Replace("__", "_")),
expectedActions.Skip(1)
);
} else {
AssertUtil.AreEqual(
actions.Select(a => a.DisplayText.Replace("__", "_")).ToArray(),
expectedActions
);
}
if (invokeAction >= 0) {
var action = actions.FirstOrDefault(a => a.DisplayText.Replace("__", "_") == expectedActions[invokeAction]);
Assert.IsNotNull(action, "No action named " + expectedActions[invokeAction]);
doc.Invoke(() => action.Invoke());
doc.WaitForText(expectedText);
}
}
} else {
doc.StartSmartTagSessionNoSession();
}
}
private static void AddSmartTagTest(string filename, int line, int column, string[] expectedActions, int invokeAction = -1, string expectedText = null) {
using (var app = new VisualStudioApp()) {
var project = app.OpenProject(@"TestData\AddImport.sln");
var item = project.ProjectItems.Item(filename);
var window = item.Open();
window.Activate();
var doc = app.GetDocument(item.Document.FullName);
AddSmartTagTest(doc, line, column, expectedActions, invokeAction, expectedText);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Baseline;
using Marten.Linq;
using Marten.Services;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Linq.Compiled
{
public class compiled_query_Tests: IntegrationContext
{
private readonly User _user1;
private readonly User _user5;
public compiled_query_Tests(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
{
_user1 = new User { FirstName = "Jeremy", UserName = "jdm", LastName = "Miller" };
var user2 = new User { FirstName = "Jens" };
var user3 = new User { FirstName = "Jeff" };
var user4 = new User { FirstName = "Corey", UserName = "myusername", LastName = "Kaylor" };
_user5 = new User { FirstName = "Jeremy", UserName = "shadetreedev", LastName = "Miller" };
theSession.Store(_user1, user2, user3, user4, _user5);
theSession.SaveChanges();
}
[Fact]
public void can_preview_command_for_a_compiled_query()
{
var cmd = theStore.Diagnostics.PreviewCommand(new UserByUsername { UserName = "hank" });
cmd.CommandText.ShouldBe("select d.id, d.data from public.mt_doc_user as d where d.data ->> 'UserName' = :p0 LIMIT :p1");
cmd.Parameters.First().Value.ShouldBe("hank");
}
[Fact]
public void can_explain_the_plan_for_a_compiled_query()
{
var query = new UserByUsername { UserName = "hank" };
var plan = theStore.Diagnostics.ExplainPlan(query);
SpecificationExtensions.ShouldNotBeNull(plan);
}
[Fact]
public void a_single_item_compiled_query()
{
var user = theSession.Query(new UserByUsername { UserName = "myusername" });
user.ShouldNotBeNull();
var differentUser = theSession.Query(new UserByUsername { UserName = "jdm" });
differentUser.UserName.ShouldBe("jdm");
}
[Fact]
public void a_single_item_compiled_query_with_fields()
{
var user = theSession.Query(new UserByUsernameWithFields { UserName = "myusername" });
SpecificationExtensions.ShouldNotBeNull(user);
var differentUser = theSession.Query(new UserByUsernameWithFields { UserName = "jdm" });
differentUser.UserName.ShouldBe("jdm");
}
[Fact]
public void a_single_item_compiled_query_SingleOrDefault()
{
var user = theSession.Query(new UserByUsernameSingleOrDefault() { UserName = "myusername" });
user.ShouldNotBeNull();
theSession.Query(new UserByUsernameSingleOrDefault() { UserName = "nonexistent" }).ShouldBeNull();
}
[Fact]
public async Task a_filtered_list_compiled_query_AsJson()
{
var user = await theSession.ToJsonMany(new FindJsonUsersByUsername() { FirstName = "Jeremy" });
user.ShouldNotBeNull();
}
[Fact]
public void several_parameters_for_compiled_query()
{
var user = theSession.Query(new FindUserByAllTheThings { Username = "jdm", FirstName = "Jeremy", LastName = "Miller" });
SpecificationExtensions.ShouldNotBeNull(user);
user.UserName.ShouldBe("jdm");
user = theSession.Query(new FindUserByAllTheThings { Username = "shadetreedev", FirstName = "Jeremy", LastName = "Miller" });
SpecificationExtensions.ShouldNotBeNull(user);
user.UserName.ShouldBe("shadetreedev");
}
[Fact]
public async Task a_single_item_compiled_query_async()
{
var user = await theSession.QueryAsync(new UserByUsername { UserName = "myusername" });
SpecificationExtensions.ShouldNotBeNull(user);
var differentUser = await theSession.QueryAsync(new UserByUsername { UserName = "jdm" });
differentUser.UserName.ShouldBe("jdm");
}
[Fact]
public async Task a_single_item_compiled_query_streamed_hit()
{
var stream = new MemoryStream();
var wasFound = await theSession.StreamJsonOne(new UserByUsername { UserName = "myusername" }, stream);
wasFound.ShouldBe(true);
stream.Position = 0;
var user = theStore.Options.Serializer().FromJson<User>(stream);
user.UserName.ShouldBe("myusername");
}
[Fact]
public async Task a_single_item_compiled_query_to_json_hit()
{
var json = await theSession.ToJsonOne(new UserByUsername { UserName = "myusername" });
var stream = new MemoryStream();
var writer = new StreamWriter(stream) {AutoFlush = true};
await writer.WriteAsync(json);
stream.Position = 0;
var user = theStore.Options.Serializer().FromJson<User>(stream);
user.UserName.ShouldBe("myusername");
}
[Fact]
public async Task a_single_item_compiled_query_streamed_miss()
{
var stream = new MemoryStream();
var wasFound = await theSession.StreamJsonOne(new UserByUsername { UserName = "nonexistent" }, stream);
wasFound.ShouldBeFalse();
stream.Length.ShouldBe(0);
}
[Fact]
public async Task a_single_item_compiled_query_to_one_json_miss()
{
var json = await theSession.ToJsonOne(new UserByUsername { UserName = "nonexistent" });
json.ShouldBeNull();
}
[Fact]
public void a_list_query_compiled()
{
var users = theSession.Query(new UsersByFirstName { FirstName = "Jeremy" }).ToList();
users.Count.ShouldBe(2);
users.ElementAt(0).UserName.ShouldBe("jdm");
users.ElementAt(1).UserName.ShouldBe("shadetreedev");
var differentUsers = theSession.Query(new UsersByFirstName { FirstName = "Jeremy" });
differentUsers.Count().ShouldBe(2);
}
[Fact]
public void a_list_query_with_fields_compiled()
{
var users = theSession.Query(new UsersByFirstNameWithFields { FirstName = "Jeremy" }).ToList();
users.Count.ShouldBe(2);
users.ElementAt(0).UserName.ShouldBe("jdm");
users.ElementAt(1).UserName.ShouldBe("shadetreedev");
var differentUsers = theSession.Query(new UsersByFirstNameWithFields { FirstName = "Jeremy" });
differentUsers.Count().ShouldBe(2);
}
[Fact]
public async Task a_list_query_compiled_async()
{
var users = await theSession.QueryAsync(new UsersByFirstName { FirstName = "Jeremy" });
users.Count().ShouldBe(2);
users.ElementAt(0).UserName.ShouldBe("jdm");
users.ElementAt(1).UserName.ShouldBe("shadetreedev");
var differentUsers = await theSession.QueryAsync(new UsersByFirstName { FirstName = "Jeremy" });
differentUsers.Count().ShouldBe(2);
}
[Fact]
public async Task to_json_many()
{
var userJson = await theSession.ToJsonMany(new UsersByFirstName { FirstName = "Jeremy" });
var stream = new MemoryStream();
var writer = new StreamWriter(stream) {AutoFlush = true};
await writer.WriteAsync(userJson);
stream.Position = 0;
var users = theStore.Options.Serializer().FromJson<User[]>(stream);
users.Count().ShouldBe(2);
users.ElementAt(0).UserName.ShouldBe("jdm");
users.ElementAt(1).UserName.ShouldBe("shadetreedev");
}
[Fact]
public async Task stream_json_many()
{
var stream = new MemoryStream();
var count = await theSession.StreamJsonMany(new UsersByFirstName { FirstName = "Jeremy" }, stream);
count.ShouldBe(2);
stream.Position = 0;
var users = theStore.Options.Serializer().FromJson<User[]>(stream);
users.Count().ShouldBe(2);
users.ElementAt(0).UserName.ShouldBe("jdm");
users.ElementAt(1).UserName.ShouldBe("shadetreedev");
}
[Fact]
public void count_query_compiled()
{
var userCount = theSession.Query(new UserCountByFirstName { FirstName = "Jeremy" });
userCount.ShouldBe(2);
userCount = theSession.Query(new UserCountByFirstName { FirstName = "Corey" });
userCount.ShouldBe(1);
}
[Fact]
public void projection_query_compiled()
{
var user = theSession.Query(new UserProjectionToLoginPayload { UserName = "jdm" });
user.ShouldNotBeNull();
user.Username.ShouldBe("jdm");
user = theSession.Query(new UserProjectionToLoginPayload { UserName = "shadetreedev" });
user.ShouldNotBeNull();
user.Username.ShouldBe("shadetreedev");
}
[Fact]
public async Task bug_1090_Any_with_compiled_queries()
{
// Really just a smoke test now
(await theSession.QueryAsync(new CompiledQuery1())).ShouldNotBeNull();
(await theSession.QueryAsync(new CompiledQuery2())).ShouldNotBeNull();
}
[Fact]
public async Task Bug_1623_use_any_within_compiled_query()
{
var user = new User {Age = 5, UserName = "testUser"};
theSession.Store(user);
await theSession.SaveChangesAsync();
// this should pass => Any works.
user.ShouldSatisfyAllConditions(
() => theSession.Query<User>().Any(x => x.Age == 6).ShouldBeFalse(),
() => theSession.Query<User>().Any(x => x.Age == 5).ShouldBeTrue()
);
// this should pass => AnyAsync works, too
var asyncR1 = await theSession.Query<User>().AnyAsync(x => x.Age == 6);
asyncR1.ShouldBeFalse();
var asyncR2 = await theSession.Query<User>().AnyAsync(x => x.Age == 5);
asyncR2.ShouldBeTrue();
var q = new TestQuery() {Age = 6};
var queryAsync = theSession.Query(q); // theSession.QueryAsync(q, default) will fail also!
queryAsync.ShouldBeFalse();
}
public class TestQuery: ICompiledQuery<User, bool>
{
public Expression<Func<IMartenQueryable<User>, bool>> QueryIs()
{
return query => query.Any(x => x.Age == Age);
}
public int Age { get; set; }
}
}
#region sample_FindUserByAllTheThings
public class FindUserByAllTheThings: ICompiledQuery<User>
{
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
return query =>
query.Where(x => x.FirstName == FirstName && Username == x.UserName)
.Where(x => x.LastName == LastName)
.Single();
}
}
#endregion
#region sample_CompiledAsJson
public class FindJsonUserByUsername: ICompiledQuery<User>
{
public string Username { get; set; }
Expression<Func<IMartenQueryable<User>, User>> ICompiledQuery<User, User>.QueryIs()
{
return query =>
query.Where(x => Username == x.UserName).Single();
}
}
#endregion
#region sample_CompiledToJsonArray
public class FindJsonOrderedUsersByUsername: ICompiledListQuery<User>
{
public string FirstName { get; set; }
Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> ICompiledQuery<User, IEnumerable<User>>.QueryIs()
{
return query =>
query.Where(x => FirstName == x.FirstName)
.OrderBy(x => x.UserName);
}
}
#endregion
public class FindJsonUsersByUsername: ICompiledListQuery<User>
{
public string FirstName { get; set; }
Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> ICompiledQuery<User, IEnumerable<User>>.QueryIs()
{
return query =>
query.Where(x => FirstName == x.FirstName);
}
}
[Collection("compiled")]
public class when_using_open_generic_compiled_query: OneOffConfigurationsContext
{
public when_using_open_generic_compiled_query() : base("compiled")
{
}
[Fact]
public async Task can_use_a_generic_compiled_query()
{
StoreOptions(opts =>
{
opts.Schema.For<User>().AddSubClass<AdminUser>();
});
theSession.Store(new AdminUser{UserName = "Harry"}, new User{UserName = "Harry"}, new AdminUser{UserName = "Sue"});
await theSession.SaveChangesAsync();
var user = await theSession.QueryAsync(new FindUserByUserName<AdminUser> { UserName = "Harry" });
user.ShouldNotBeNull();
}
}
public class FindUserByUserName<TUser>: ICompiledQuery<TUser, TUser> where TUser : User
{
public Expression<Func<IMartenQueryable<TUser>, TUser>> QueryIs()
{
return q => q.FirstOrDefault(x => x.UserName == UserName);
}
public string UserName { get; set; }
}
[Collection("multi_tenancy")]
public class when_compiled_queries_are_used_in_multi_tenancy: OneOffConfigurationsContext
{
private readonly ITestOutputHelper _output;
public when_compiled_queries_are_used_in_multi_tenancy(ITestOutputHelper output) : base("multi_tenancy")
{
_output = output;
}
[Fact]
public async Task compile_query_honors_the_current_tenant()
{
StoreOptions(opts => opts.Schema.For<User>().MultiTenanted());
var hanOne = new User{UserName = "han"};
using (var session = theStore.LightweightSession("one"))
{
session.Store(hanOne);
session.Store(new User{UserName = "luke"});
session.Store(new User{UserName = "leia"});
await session.SaveChangesAsync();
}
var hanTwo = new User{UserName = "han"};
using (var session = theStore.LightweightSession("two"))
{
session.Store(hanTwo);
session.Store(new User{UserName = "luke"});
session.Store(new User{UserName = "vader"});
session.Store(new User{UserName = "yoda"});
await session.SaveChangesAsync();
}
using var query = theStore.QuerySession("one");
query.Logger = new TestOutputMartenLogger(_output);
var user = await query.QueryAsync(new UserByUsernameWithFields {UserName = "han"});
user.Id.ShouldBe(hanOne.Id);
}
#region sample_using_QueryStatistics_with_compiled_query
[Fact]
public async Task use_compiled_query_with_statistics()
{
await theStore.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Target));
var targets = Target.GenerateRandomData(100).ToArray();
await theStore.BulkInsertAsync(targets);
var query = new TargetsInOrder
{
PageSize = 10,
Start = 20
};
var results = await theSession.QueryAsync(query);
// Verifying that the total record count in the database matching
// the query is determined when this is executed
query.Statistics.TotalResults.ShouldBe(100);
}
#endregion
[Fact]
public void can_preview_generated_source_code()
{
var sourceCode = theStore.Advanced
.SourceCodeForCompiledQuery(typeof(FindJsonUserByUsername));
// xunit output helper
_output.WriteLine(sourceCode);
}
}
public class UserProjectionToLoginPayload: ICompiledQuery<User, LoginPayload>
{
public string UserName { get; set; }
public Expression<Func<IMartenQueryable<User>, LoginPayload>> QueryIs()
{
return query => query.Where(x => x.UserName == UserName)
.Select(x => new LoginPayload { Username = x.UserName }).Single();
}
}
public class LoginPayload
{
public string Username { get; set; }
}
#region sample_TargetsInOrder
public class TargetsInOrder: ICompiledListQuery<Target>
{
// This is all you need to do
public QueryStatistics Statistics { get; } = new QueryStatistics();
public int PageSize { get; set; } = 20;
public int Start { get; set; } = 5;
Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> ICompiledQuery<Target, IEnumerable<Target>>.QueryIs()
{
return q => q
.OrderBy(x => x.Id).Skip(Start).Take(PageSize);
}
}
#endregion
public class UserCountByFirstName: ICompiledQuery<User, int>
{
public string FirstName { get; set; }
public Expression<Func<IMartenQueryable<User>, int>> QueryIs()
{
return query => query.Count(x => x.FirstName == FirstName);
}
}
public class UserByUsername: ICompiledQuery<User>
{
public string UserName { get; set; }
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
return query => query
.FirstOrDefault(x => x.UserName == UserName);
}
}
public class UserByUsernameWithFields: ICompiledQuery<User>
{
public string UserName;
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
return query => Queryable.FirstOrDefault(query.Where(x => x.UserName == UserName));
}
}
public class UserByUsernameSingleOrDefault: ICompiledQuery<User>
{
public static int Count;
public string UserName { get; set; }
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
Count++;
return query => query.Where(x => x.UserName == UserName)
.SingleOrDefault();
}
}
#region sample_UsersByFirstName-Query
public class UsersByFirstName: ICompiledListQuery<User>
{
public static int Count;
public string FirstName { get; set; }
public Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> QueryIs()
{
return query => query.Where(x => x.FirstName == FirstName);
}
}
#endregion
public class UsersByFirstNameWithFields: ICompiledListQuery<User>
{
public string FirstName;
public Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> QueryIs()
{
return query => query.Where(x => x.FirstName == FirstName);
}
}
#region sample_UserNamesForFirstName
public class UserNamesForFirstName: ICompiledListQuery<User, string>
{
public Expression<Func<IMartenQueryable<User>, IEnumerable<string>>> QueryIs()
{
return q => q
.Where(x => x.FirstName == FirstName)
.Select(x => x.UserName);
}
public string FirstName { get; set; }
}
#endregion
public class CompiledQuery1 : ICompiledQuery<Target, bool>
{
public string StringValue { get; set; }
public Expression<Func<IMartenQueryable<Target>, bool>> QueryIs()
{
return q => q.Any(x => x.String.EqualsIgnoreCase(StringValue));
}
}
public class CompiledQuery2 : ICompiledQuery<Target, bool>
{
public Guid IdValue { get; set; }
public Expression<Func<IMartenQueryable<Target>, bool>> QueryIs()
{
return q => q.Any(x => x.Id == IdValue);
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Infrastructure {
sealed class TaskDialog {
private readonly IServiceProvider _provider;
private readonly List<TaskDialogButton> _buttons;
private readonly List<TaskDialogButton> _radioButtons;
public TaskDialog(IServiceProvider provider) {
_provider = provider;
_buttons = new List<TaskDialogButton>();
_radioButtons = new List<TaskDialogButton>();
UseCommandLinks = true;
}
public static TaskDialog ForException(
IServiceProvider provider,
Exception exception,
string message = null,
string issueTrackerUrl = null
) {
string suffix = string.IsNullOrEmpty(issueTrackerUrl) ?
Strings.UnexpectedError_Instruction :
Strings.UnexpectedError_InstructionWithLink;
if (string.IsNullOrEmpty(message)) {
message = suffix;
} else {
message += Environment.NewLine + Environment.NewLine + suffix;
}
var td = new TaskDialog(provider) {
MainInstruction = Strings.UnexpectedError_Title,
Content = message,
EnableHyperlinks = true,
CollapsedControlText = Strings.ShowDetails,
ExpandedControlText = Strings.HideDetails,
ExpandedInformation = "```{0}Build: {2}{0}{0}{1}{0}```".FormatUI(Environment.NewLine, exception, AssemblyVersionInfo.Version)
};
td.Buttons.Add(TaskDialogButton.Close);
if (!string.IsNullOrEmpty(issueTrackerUrl)) {
td.HyperlinkClicked += (s, e) => {
if (e.Url == "issuetracker") {
Process.Start(issueTrackerUrl);
}
};
}
return td;
}
public static void CallWithRetry(
Action<int> action,
IServiceProvider provider,
string title,
string failedText,
string expandControlText,
string retryButtonText,
string cancelButtonText,
Func<Exception, bool> canRetry = null
) {
for (int retryCount = 1; ; ++retryCount) {
try {
action(retryCount);
return;
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
if (canRetry != null && !canRetry(ex)) {
throw;
}
var td = new TaskDialog(provider) {
Title = title,
MainInstruction = failedText,
Content = ex.Message,
CollapsedControlText = expandControlText,
ExpandedControlText = expandControlText,
ExpandedInformation = ex.ToString()
};
var retry = new TaskDialogButton(retryButtonText);
td.Buttons.Add(retry);
td.Buttons.Add(new TaskDialogButton(cancelButtonText));
var button = td.ShowModal();
if (button != retry) {
throw new OperationCanceledException();
}
}
}
}
public static T CallWithRetry<T>(
Func<int, T> func,
IServiceProvider provider,
string title,
string failedText,
string expandControlText,
string retryButtonText,
string cancelButtonText,
Func<Exception, bool> canRetry = null
) {
for (int retryCount = 1; ; ++retryCount) {
try {
return func(retryCount);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
if (canRetry != null && !canRetry(ex)) {
throw;
}
var td = new TaskDialog(provider) {
Title = title,
MainInstruction = failedText,
Content = ex.Message,
CollapsedControlText = expandControlText,
ExpandedControlText = expandControlText,
ExpandedInformation = ex.ToString()
};
var retry = new TaskDialogButton(retryButtonText);
var cancel = new TaskDialogButton(cancelButtonText);
td.Buttons.Add(retry);
td.Buttons.Add(cancel);
var button = td.ShowModal();
if (button == cancel) {
throw new OperationCanceledException();
}
}
}
}
public TaskDialogButton ShowModal() {
var config = new NativeMethods.TASKDIALOGCONFIG();
config.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.TASKDIALOGCONFIG));
config.pButtons = IntPtr.Zero;
config.pRadioButtons = IntPtr.Zero;
var uiShell = (IVsUIShell)_provider.GetService(typeof(SVsUIShell));
if (uiShell == null) {
// We are shutting down, so return the default
return SelectedButton;
}
uiShell.GetDialogOwnerHwnd(out config.hwndParent);
uiShell.EnableModeless(0);
var customButtons = new List<TaskDialogButton>();
config.dwCommonButtons = 0;
foreach (var button in Buttons) {
var flag = GetButtonFlag(button);
if (flag != 0) {
config.dwCommonButtons |= flag;
} else {
customButtons.Add(button);
}
}
try {
if (customButtons.Any()) {
config.cButtons = (uint)customButtons.Count;
var ptr = config.pButtons = Marshal.AllocHGlobal(customButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)));
for (int i = 0; i < customButtons.Count; ++i) {
NativeMethods.TASKDIALOG_BUTTON data;
data.nButtonID = GetButtonId(null, null, i);
if (string.IsNullOrEmpty(customButtons[i].Subtext)) {
data.pszButtonText = customButtons[i].Text;
} else {
data.pszButtonText = string.Format("{0}\n{1}", customButtons[i].Text, customButtons[i].Subtext);
}
Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false);
}
} else {
config.cButtons = 0;
config.pButtons = IntPtr.Zero;
}
if (_buttons.Any() && SelectedButton != null) {
config.nDefaultButton = GetButtonId(SelectedButton, customButtons);
} else {
config.nDefaultButton = 0;
}
if (_radioButtons.Any()) {
config.cRadioButtons = (uint)_radioButtons.Count;
var ptr = config.pRadioButtons = Marshal.AllocHGlobal(_radioButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)));
for (int i = 0; i < _radioButtons.Count; ++i) {
NativeMethods.TASKDIALOG_BUTTON data;
data.nButtonID = GetRadioId(null, null, i);
data.pszButtonText = _radioButtons[i].Text;
Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false);
}
if (SelectedRadioButton != null) {
config.nDefaultRadioButton = GetRadioId(SelectedRadioButton, _radioButtons);
} else {
config.nDefaultRadioButton = 0;
}
}
config.pszWindowTitle = Title;
config.pszMainInstruction = MainInstruction;
config.pszContent = Content;
config.pszExpandedInformation = ExpandedInformation;
config.pszExpandedControlText = ExpandedControlText;
config.pszCollapsedControlText = CollapsedControlText;
config.pszFooter = Footer;
config.pszVerificationText = VerificationText;
config.pfCallback = Callback;
config.MainIcon.hMainIcon = (int)GetIconResource(MainIcon);
config.FooterIcon.hMainIcon = (int)GetIconResource(FooterIcon);
if (Width.HasValue && Width.Value != 0) {
config.cxWidth = (uint)Width.Value;
} else {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_SIZE_TO_CONTENT;
}
if (EnableHyperlinks) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ENABLE_HYPERLINKS;
}
if (AllowCancellation) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ALLOW_DIALOG_CANCELLATION;
}
if (UseCommandLinks && config.cButtons > 0) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_USE_COMMAND_LINKS;
}
if (!ShowExpandedInformationInContent) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPAND_FOOTER_AREA;
}
if (ExpandedByDefault) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPANDED_BY_DEFAULT;
}
if (SelectedVerified) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
}
if (CanMinimize) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_CAN_BE_MINIMIZED;
}
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_POSITION_RELATIVE_TO_WINDOW;
int selectedButton, selectedRadioButton;
bool verified;
ErrorHandler.ThrowOnFailure((int)NativeMethods.TaskDialogIndirect(
config,
out selectedButton,
out selectedRadioButton,
out verified
));
SelectedButton = GetButton(selectedButton, customButtons);
SelectedRadioButton = GetRadio(selectedRadioButton, _radioButtons);
SelectedVerified = verified;
} finally {
uiShell.EnableModeless(1);
if (config.pButtons != IntPtr.Zero) {
for (int i = 0; i < customButtons.Count; ++i) {
Marshal.DestroyStructure(config.pButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON));
}
Marshal.FreeHGlobal(config.pButtons);
}
if (config.pRadioButtons != IntPtr.Zero) {
for (int i = 0; i < _radioButtons.Count; ++i) {
Marshal.DestroyStructure(config.pRadioButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON));
}
Marshal.FreeHGlobal(config.pRadioButtons);
}
}
return SelectedButton;
}
private int Callback(IntPtr hwnd,
uint uNotification,
IntPtr wParam,
IntPtr lParam,
IntPtr lpRefData) {
try {
switch ((NativeMethods.TASKDIALOG_NOTIFICATIONS)uNotification) {
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_CREATED:
foreach (var btn in _buttons.Where(b => b.ElevationRequired)) {
NativeMethods.SendMessage(
hwnd,
(int)NativeMethods.TASKDIALOG_MESSAGES.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE,
new IntPtr(GetButtonId(btn, _buttons)),
new IntPtr(1)
);
}
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_NAVIGATED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_BUTTON_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_HYPERLINK_CLICKED:
var url = Marshal.PtrToStringUni(lParam);
var hevt = HyperlinkClicked;
if (hevt != null) {
hevt(this, new TaskDialogHyperlinkClickedEventArgs(url));
} else {
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
}
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_TIMER:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_DESTROYED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_RADIO_BUTTON_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_DIALOG_CONSTRUCTED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_VERIFICATION_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_HELP:
break;
case NativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_EXPANDO_BUTTON_CLICKED:
break;
default:
break;
}
return VSConstants.S_OK;
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
return Marshal.GetHRForException(ex);
}
}
public string Title { get; set; }
public string MainInstruction { get; set; }
public string Content { get; set; }
public string VerificationText { get; set; }
public string ExpandedInformation { get; set; }
public string Footer { get; set; }
public bool ExpandedByDefault { get; set; }
public bool ShowExpandedInformationInContent { get; set; }
public string ExpandedControlText { get; set; }
public string CollapsedControlText { get; set; }
public int? Width { get; set; }
public bool EnableHyperlinks { get; set; }
public bool AllowCancellation { get; set; }
public bool UseCommandLinks { get; set; }
public bool CanMinimize { get; set; }
public TaskDialogIcon MainIcon { get; set; }
public TaskDialogIcon FooterIcon { get; set; }
/// <summary>
/// Raised when a hyperlink in the dialog is clicked. If no event
/// handlers are added, the default behavior is to open an external
/// browser.
/// </summary>
public event EventHandler<TaskDialogHyperlinkClickedEventArgs> HyperlinkClicked;
public List<TaskDialogButton> Buttons {
get {
return _buttons;
}
}
public List<TaskDialogButton> RadioButtons {
get {
return _radioButtons;
}
}
public TaskDialogButton SelectedButton { get; set; }
public TaskDialogButton SelectedRadioButton { get; set; }
public bool SelectedVerified { get; set; }
private static NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS GetButtonFlag(TaskDialogButton button) {
if (button == TaskDialogButton.OK) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_OK_BUTTON;
} else if (button == TaskDialogButton.Cancel) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_CANCEL_BUTTON;
} else if (button == TaskDialogButton.Yes) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_YES_BUTTON;
} else if (button == TaskDialogButton.No) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_NO_BUTTON;
} else if (button == TaskDialogButton.Retry) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_RETRY_BUTTON;
} else if (button == TaskDialogButton.Close) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_CLOSE_BUTTON;
} else {
return 0;
}
}
private static NativeMethods.TASKDIALOG_ICON GetIconResource(TaskDialogIcon icon) {
switch (icon) {
case TaskDialogIcon.None:
return 0;
case TaskDialogIcon.Error:
return NativeMethods.TASKDIALOG_ICON.TD_ERROR_ICON;
case TaskDialogIcon.Warning:
return NativeMethods.TASKDIALOG_ICON.TD_WARNING_ICON;
case TaskDialogIcon.Information:
return NativeMethods.TASKDIALOG_ICON.TD_INFORMATION_ICON;
case TaskDialogIcon.Shield:
return NativeMethods.TASKDIALOG_ICON.TD_SHIELD_ICON;
default:
throw new ArgumentException("Invalid TaskDialogIcon value", "icon");
}
}
private static int GetButtonId(
TaskDialogButton button,
IList<TaskDialogButton> customButtons = null,
int indexHint = -1
) {
if (indexHint >= 0) {
return indexHint + 1000;
}
if (button == TaskDialogButton.OK) {
return NativeMethods.IDOK;
} else if (button == TaskDialogButton.Cancel) {
return NativeMethods.IDCANCEL;
} else if (button == TaskDialogButton.Yes) {
return NativeMethods.IDYES;
} else if (button == TaskDialogButton.No) {
return NativeMethods.IDNO;
} else if (button == TaskDialogButton.Retry) {
return NativeMethods.IDRETRY;
} else if (button == TaskDialogButton.Close) {
return NativeMethods.IDCLOSE;
} else if (customButtons != null) {
int i = customButtons.IndexOf(button);
if (i >= 0) {
return i + 1000;
}
}
return -1;
}
private static TaskDialogButton GetButton(int id, IList<TaskDialogButton> customButtons = null) {
switch (id) {
case NativeMethods.IDOK:
return TaskDialogButton.OK;
case NativeMethods.IDCANCEL:
return TaskDialogButton.Cancel;
case NativeMethods.IDYES:
return TaskDialogButton.Yes;
case NativeMethods.IDNO:
return TaskDialogButton.No;
case NativeMethods.IDRETRY:
return TaskDialogButton.Retry;
case NativeMethods.IDCLOSE:
return TaskDialogButton.Close;
}
if (customButtons != null && id >= 1000 && id - 1000 < customButtons.Count) {
return customButtons[id - 1000];
}
return null;
}
private static int GetRadioId(
TaskDialogButton button,
IList<TaskDialogButton> buttons,
int indexHint = -1
) {
if (indexHint >= 0) {
return indexHint + 2000;
}
return buttons.IndexOf(button) + 2000;
}
private static TaskDialogButton GetRadio(int id, IList<TaskDialogButton> buttons) {
if (id >= 2000 && id - 2000 < buttons.Count) {
return buttons[id - 2000];
}
return null;
}
private static class NativeMethods {
internal const int IDOK = 1;
internal const int IDCANCEL = 2;
internal const int IDABORT = 3;
internal const int IDRETRY = 4;
internal const int IDIGNORE = 5;
internal const int IDYES = 6;
internal const int IDNO = 7;
internal const int IDCLOSE = 8;
internal const int WM_USER = 0x0400;
internal static IntPtr NO_PARENT = IntPtr.Zero;
[DllImport(ExternDll.User32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr SendMessage(
IntPtr hWnd,
uint msg,
IntPtr wParam,
IntPtr lParam
);
[DllImport(ExternDll.ComCtl32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern HRESULT TaskDialog(
IntPtr hwndParent,
IntPtr hInstance,
[MarshalAs(UnmanagedType.LPWStr)] string pszWindowtitle,
[MarshalAs(UnmanagedType.LPWStr)] string pszMainInstruction,
[MarshalAs(UnmanagedType.LPWStr)] string pszContent,
NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons,
[MarshalAs(UnmanagedType.LPWStr)] string pszIcon,
[In, Out] ref int pnButton);
[DllImport(ExternDll.ComCtl32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern HRESULT TaskDialogIndirect(
[In] NativeMethods.TASKDIALOGCONFIG pTaskConfig,
[Out] out int pnButton,
[Out] out int pnRadioButton,
[MarshalAs(UnmanagedType.Bool)][Out] out bool pVerificationFlagChecked);
internal delegate HRESULT TDIDelegate(
[In] NativeMethods.TASKDIALOGCONFIG pTaskConfig,
[Out] out int pnButton,
[Out] out int pnRadioButton,
[Out] out bool pVerificationFlagChecked);
// Main task dialog configuration struct.
// NOTE: Packing must be set to 4 to make this work on 64-bit platforms.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
internal class TASKDIALOGCONFIG {
internal uint cbSize;
internal IntPtr hwndParent;
internal IntPtr hInstance;
internal TASKDIALOG_FLAGS dwFlags;
internal TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszWindowTitle;
internal TASKDIALOGCONFIG_ICON_UNION MainIcon; // NOTE: 32-bit union field, holds pszMainIcon as well
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszMainInstruction;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszContent;
internal uint cButtons;
internal IntPtr pButtons; // Ptr to TASKDIALOG_BUTTON structs
internal int nDefaultButton;
internal uint cRadioButtons;
internal IntPtr pRadioButtons; // Ptr to TASKDIALOG_BUTTON structs
internal int nDefaultRadioButton;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszVerificationText;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszExpandedInformation;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszExpandedControlText;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszCollapsedControlText;
internal TASKDIALOGCONFIG_ICON_UNION FooterIcon; // NOTE: 32-bit union field, holds pszFooterIcon as well
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszFooter;
internal PFTASKDIALOGCALLBACK pfCallback;
internal IntPtr lpCallbackData;
internal uint cxWidth;
}
internal const int IGNORED = (int)HRESULT.S_OK;
// NOTE: We include a "spacer" so that the struct size varies on
// 64-bit architectures.
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
internal struct TASKDIALOGCONFIG_ICON_UNION {
internal TASKDIALOGCONFIG_ICON_UNION(int i) {
spacer = IntPtr.Zero;
pszIcon = 0;
hMainIcon = i;
}
[FieldOffset(0)]
internal int hMainIcon;
[FieldOffset(0)]
internal int pszIcon;
[FieldOffset(0)]
internal IntPtr spacer;
}
// NOTE: Packing must be set to 4 to make this work on 64-bit platforms.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
internal struct TASKDIALOG_BUTTON {
public TASKDIALOG_BUTTON(int n, string txt) {
nButtonID = n;
pszButtonText = txt;
}
internal int nButtonID;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszButtonText;
}
// Task Dialog - identifies common buttons.
[Flags]
internal enum TASKDIALOG_COMMON_BUTTON_FLAGS {
TDCBF_OK_BUTTON = 0x0001, // selected control return value IDOK
TDCBF_YES_BUTTON = 0x0002, // selected control return value IDYES
TDCBF_NO_BUTTON = 0x0004, // selected control return value IDNO
TDCBF_CANCEL_BUTTON = 0x0008, // selected control return value IDCANCEL
TDCBF_RETRY_BUTTON = 0x0010, // selected control return value IDRETRY
TDCBF_CLOSE_BUTTON = 0x0020 // selected control return value IDCLOSE
}
// Identify button *return values* - note that, unfortunately, these are different
// from the inbound button values.
internal enum TASKDIALOG_COMMON_BUTTON_RETURN_ID {
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8
}
// Task Dialog - flags
[Flags]
internal enum TASKDIALOG_FLAGS {
NONE = 0,
TDF_ENABLE_HYPERLINKS = 0x0001,
TDF_USE_HICON_MAIN = 0x0002,
TDF_USE_HICON_FOOTER = 0x0004,
TDF_ALLOW_DIALOG_CANCELLATION = 0x0008,
TDF_USE_COMMAND_LINKS = 0x0010,
TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020,
TDF_EXPAND_FOOTER_AREA = 0x0040,
TDF_EXPANDED_BY_DEFAULT = 0x0080,
TDF_VERIFICATION_FLAG_CHECKED = 0x0100,
TDF_SHOW_PROGRESS_BAR = 0x0200,
TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400,
TDF_CALLBACK_TIMER = 0x0800,
TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000,
TDF_RTL_LAYOUT = 0x2000,
TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000,
TDF_CAN_BE_MINIMIZED = 0x8000,
TDF_SIZE_TO_CONTENT = 0x01000000
}
internal enum TASKDIALOG_MESSAGES {
TDM_NAVIGATE_PAGE = WM_USER + 101,
TDM_CLICK_BUTTON = WM_USER + 102, // wParam = Button ID
TDM_SET_MARQUEE_PROGRESS_BAR = WM_USER + 103, // wParam = 0 (nonMarque) wParam != 0 (Marquee)
TDM_SET_PROGRESS_BAR_STATE = WM_USER + 104, // wParam = new progress state
TDM_SET_PROGRESS_BAR_RANGE = WM_USER + 105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
TDM_SET_PROGRESS_BAR_POS = WM_USER + 106, // wParam = new position
TDM_SET_PROGRESS_BAR_MARQUEE = WM_USER + 107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints)
TDM_SET_ELEMENT_TEXT = WM_USER + 108, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
TDM_CLICK_RADIO_BUTTON = WM_USER + 110, // wParam = Radio Button ID
TDM_ENABLE_BUTTON = WM_USER + 111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID
TDM_ENABLE_RADIO_BUTTON = WM_USER + 112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID
TDM_CLICK_VERIFICATION = WM_USER + 113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus)
TDM_UPDATE_ELEMENT_TEXT = WM_USER + 114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = WM_USER + 115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required)
TDM_UPDATE_ICON = WM_USER + 116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
}
internal enum TASKDIALOG_ICON : ushort {
TD_WARNING_ICON = unchecked((ushort)-1),
TD_ERROR_ICON = unchecked((ushort)-2),
TD_INFORMATION_ICON = unchecked((ushort)-3),
TD_SHIELD_ICON = unchecked((ushort)-4)
}
internal enum TASKDIALOG_NOTIFICATIONS {
TDN_CREATED = 0,
TDN_NAVIGATED = 1,
TDN_BUTTON_CLICKED = 2, // wParam = Button ID
TDN_HYPERLINK_CLICKED = 3, // lParam = (LPCWSTR)pszHREF
TDN_TIMER = 4, // wParam = Milliseconds since dialog created or timer reset
TDN_DESTROYED = 5,
TDN_RADIO_BUTTON_CLICKED = 6, // wParam = Radio Button ID
TDN_DIALOG_CONSTRUCTED = 7,
TDN_VERIFICATION_CLICKED = 8, // wParam = 1 if checkbox checked, 0 if not, lParam is unused and always 0
TDN_HELP = 9,
TDN_EXPANDO_BUTTON_CLICKED = 10 // wParam = 0 (dialog is now collapsed), wParam != 0 (dialog is now expanded)
}
// Task Dialog config and related structs (for TaskDialogIndirect())
internal delegate int PFTASKDIALOGCALLBACK(
IntPtr hwnd,
uint msg,
IntPtr wParam,
IntPtr lParam,
IntPtr lpRefData);
// Misc small classes and enums
internal enum HRESULT : long {
S_FALSE = 0x0001,
S_OK = 0x0000,
E_INVALIDARG = 0x80070057,
E_OUTOFMEMORY = 0x8007000E
}
// Window States
internal enum NativeDialogShowState {
PreShow,
Showing,
Closing,
Closed
}
internal class ExternDll {
internal const string ComCtl32 = "comctl32.dll";
internal const string Kernel32 = "kernel32.dll";
internal const string ComDlg32 = "comdlg32.dll";
internal const string User32 = "user32.dll";
internal const string Shell32 = "shell32.dll";
}
/// <summary>
/// Identifies one of the standard buttons that
/// can be displayed via TaskDialog.
/// </summary>
[Flags]
internal enum TaskDialogStandardButton {
None = 0x0000,
Ok = 0x0001,
Yes = 0x0002,
No = 0x0004,
Cancel = 0x0008,
Retry = 0x0010,
Close = 0x0020
}
/// <summary>
/// Provides standard combinations of standard buttons in the TaskDialog.
/// </summary>
internal enum TaskDialogStandardButtons {
None = TaskDialogStandardButton.None,
Cancel = TaskDialogStandardButton.Cancel,
OkCancel = TaskDialogStandardButton.Ok | TaskDialogStandardButton.Cancel,
Yes = TaskDialogStandardButton.Yes,
YesNo = TaskDialogStandardButton.Yes | TaskDialogStandardButton.No,
YesNoCancel = TaskDialogStandardButton.Yes | TaskDialogStandardButton.No | TaskDialogStandardButton.Cancel,
RetryCancel = TaskDialogStandardButton.Retry | TaskDialogStandardButton.Cancel,
Close = TaskDialogStandardButton.Close
}
/// <summary>
/// Specifies the icon displayed in a task dialog.
/// </summary>
internal enum TaskDialogStandardIcon {
Warning = 65535,
Error = 65534,
Information = 65533,
Shield = 65532,
ShieldBlueBG = 65531,
SecurityWarning = 65530,
SecurityError = 65529,
SecuritySuccess = 65528,
SecurityShieldGray = 65527
}
internal static bool Failed(HRESULT hresult) {
return ((int)hresult < 0);
}
}
}
sealed class TaskDialogButton {
public TaskDialogButton(string text) {
int i = text.IndexOfAny(Environment.NewLine.ToCharArray());
if (i < 0) {
Text = text;
} else {
Text = text.Remove(i);
Subtext = text.Substring(i).TrimStart();
}
}
public TaskDialogButton(string text, string subtext) {
Text = text;
Subtext = subtext;
}
public string Text { get; set; }
public string Subtext { get; set; }
public bool ElevationRequired { get; set; }
private TaskDialogButton() { }
public static readonly TaskDialogButton OK = new TaskDialogButton();
public static readonly TaskDialogButton Cancel = new TaskDialogButton();
public static readonly TaskDialogButton Yes = new TaskDialogButton();
public static readonly TaskDialogButton No = new TaskDialogButton();
public static readonly TaskDialogButton Retry = new TaskDialogButton();
public static readonly TaskDialogButton Close = new TaskDialogButton();
}
sealed class TaskDialogHyperlinkClickedEventArgs : EventArgs {
public TaskDialogHyperlinkClickedEventArgs(string url) {
Url = url;
}
public string Url { get; }
}
enum TaskDialogIcon {
None,
Error,
Warning,
Information,
Shield
}
}
| |
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using SoundCloud.Api.Entities.Base;
using SoundCloud.Api.Entities.Enums;
using SoundCloud.Api.Exceptions;
using SoundCloud.Api.Login;
using SoundCloud.Api.Utils;
namespace SoundCloud.Api.Entities
{
/// <summary>
/// Represents different the credentials used for authentication.
/// </summary>
public sealed class Credentials : Entity
{
/// <summary>
/// Available for GET requests
/// </summary>
[JsonProperty("access_token")]
public string AccessToken { get; set; }
/// <summary>
/// Available for POST requests
/// The client id belonging to your application
/// </summary>
[JsonProperty("client_id")]
public string ClientId { get; set; }
/// <summary>
/// Available for POST requests
/// The client secret belonging to your application
/// </summary>
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
/// <summary>
/// Available for POST requests
/// The authorization code obtained when user is sent to redirect_uri
/// </summary>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// Available for GET requests
/// </summary>
[JsonProperty("expires_in")]
public int? ExpiresIn { get; set; }
/// <summary>
/// Available for POST requests
/// </summary>
[JsonProperty("password")]
public string Password { get; set; }
/// <summary>
/// Available for POST requests
/// The redirect uri you have configured for your application
/// </summary>
[JsonProperty("redirect_uri")]
public string RedirectUri { get; set; }
/// <summary>
/// Available for POST requests
/// </summary>
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
/// <summary>
/// Available for GET requests
/// </summary>
[JsonProperty("scope")]
public Scope Scope { get; set; }
/// <summary>
/// Available for POST requests
/// </summary>
[JsonProperty("username")]
public string Username { get; set; }
public void ValidateAuthorizationCode()
{
var messages = new ValidationMessages();
if (string.IsNullOrEmpty(ClientId))
{
messages.Add("ClientId missing. Use the client_id property to set the ClientId.");
}
if (string.IsNullOrEmpty(ClientSecret))
{
messages.Add("ClientSecret missing. Use the client_secret property to set the ClientSecret.");
}
if (string.IsNullOrEmpty(Code))
{
messages.Add("Code missing. Use the code property to set the Code.");
}
if (messages.HasErrors)
{
throw new SoundCloudValidationException(messages);
}
}
public void ValidateClientCredentials()
{
var messages = new ValidationMessages();
if (string.IsNullOrEmpty(ClientId))
{
messages.Add("ClientId missing. Use the client_id property to set the ClientId.");
}
if (string.IsNullOrEmpty(ClientSecret))
{
messages.Add("ClientSecret missing. Use the client_secret property to set the ClientSecret.");
}
if (messages.HasErrors)
{
throw new SoundCloudValidationException(messages);
}
}
public void ValidatePassword()
{
var messages = new ValidationMessages();
if (string.IsNullOrEmpty(ClientId))
{
messages.Add("ClientId missing. Use the client_id property to set the ClientId.");
}
if (string.IsNullOrEmpty(ClientSecret))
{
messages.Add("ClientSecret missing. Use the client_secret property to set the ClientSecret.");
}
if (string.IsNullOrEmpty(Username))
{
messages.Add("Username missing. Use the username property to set the Username.");
}
if (string.IsNullOrEmpty(Password))
{
messages.Add("Password missing. Use the password property to set the Password.");
}
if (messages.HasErrors)
{
throw new SoundCloudValidationException(messages);
}
}
public void ValidateRefreshToken()
{
var messages = new ValidationMessages();
if (string.IsNullOrEmpty(ClientId))
{
messages.Add("ClientId missing. Use the client_id property to set the ClientId.");
}
if (string.IsNullOrEmpty(ClientSecret))
{
messages.Add("ClientSecret missing. Use the client_secret property to set the ClientSecret.");
}
if (string.IsNullOrEmpty(RefreshToken))
{
messages.Add("RefreshToken missing. Use the refresh_token property to set the RefreshToken.");
}
if (messages.HasErrors)
{
throw new SoundCloudValidationException(messages);
}
}
internal IDictionary<string, object> ToParameters(GrantType type)
{
var parameters = new Dictionary<string, object>();
parameters.Add("grant_type", type.GetAttributeOfType<EnumMemberAttribute>().Value);
switch (type)
{
case GrantType.RefreshToken:
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);
parameters.Add("refresh_token", RefreshToken);
break;
case GrantType.Password:
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);
parameters.Add("username", Username);
parameters.Add("password", Password);
break;
case GrantType.ClientCredentials:
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);
break;
case GrantType.AuthorizationCode:
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);
parameters.Add("code", Code);
break;
default:
return parameters;
}
return parameters;
}
}
}
| |
/*
* 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 System.Timers;
using log4net;
using Nini.Config;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Region.CoreModules.World.Voxels;
using OpenSim.Region.Framework.Scenes;
using PumaCode.SvnDotNet.AprSharp;
using PumaCode.SvnDotNet.SubversionSharp;
using Slash = System.IO.Path;
namespace OpenSim.Region.Modules.SvnSerialiser
{
public class SvnBackupModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_scenes;
private Timer m_timer;
private bool m_enabled;
private bool m_installBackupOnLoad;
private IRegionSerialiserModule m_serialiser;
private bool m_svnAutoSave;
private SvnClient m_svnClient;
private string m_svndir = "SVNmodule" + Slash.DirectorySeparatorChar + "repo";
private string m_svnpass = "password";
private TimeSpan m_svnperiod = new TimeSpan(0, 0, 15, 0, 0);
private string m_svnurl = "svn://insert.Your.svn/here/";
private string m_svnuser = "username";
#region SvnModule Core
/// <summary>
/// Exports a specified scene to the SVN repo directory, then commits.
/// </summary>
/// <param name="scene">The scene to export</param>
public void SaveRegion(Scene scene)
{
List<string> svnfilenames = CreateAndAddExport(scene);
m_svnClient.Commit3(svnfilenames, true, false);
m_log.Info("[SVNBACKUP]: Region backup successful (" + scene.RegionInfo.RegionName + ").");
}
/// <summary>
/// Saves all registered scenes to the SVN repo, then commits.
/// </summary>
public void SaveAllRegions()
{
List<string> svnfilenames = new List<string>();
List<string> regions = new List<string>();
foreach (Scene scene in m_scenes)
{
svnfilenames.AddRange(CreateAndAddExport(scene));
regions.Add("'" + scene.RegionInfo.RegionName + "' ");
}
m_svnClient.Commit3(svnfilenames, true, false);
m_log.Info("[SVNBACKUP]: Server backup successful (" + String.Concat(regions.ToArray()) + ").");
}
private List<string> CreateAndAddExport(Scene scene)
{
m_log.Info("[SVNBACKUP]: Saving a region to SVN with name " + scene.RegionInfo.RegionName);
List<string> filenames = m_serialiser.SerialiseRegion(scene, m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar);
try
{
m_svnClient.Add3(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID, true, false, false);
}
catch (SvnException)
{
}
List<string> svnfilenames = new List<string>();
foreach (string filename in filenames)
svnfilenames.Add(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar + filename);
svnfilenames.Add(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID);
return svnfilenames;
}
public void LoadRegion(Scene scene)
{
IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
{
serialiser.LoadPrimsFromXml2(
scene,
m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID
+ Slash.DirectorySeparatorChar + "objects.xml");
scene.RequestModuleInterface<IVoxelModule>().LoadFromFile(
m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID
+ Slash.DirectorySeparatorChar + "terrain.osvox");
m_log.Info("[SVNBACKUP]: Region load successful (" + scene.RegionInfo.RegionName + ").");
}
else
{
m_log.ErrorFormat(
"[SVNBACKUP]: Region load of {0} failed - no serialisation module available",
scene.RegionInfo.RegionName);
}
}
private void CheckoutSvn()
{
m_svnClient.Checkout2(m_svnurl, m_svndir, Svn.Revision.Head, Svn.Revision.Head, true, false);
}
private void CheckoutSvn(SvnRevision revision)
{
m_svnClient.Checkout2(m_svnurl, m_svndir, revision, revision, true, false);
}
// private void CheckoutSvnPartial(string subdir)
// {
// if (!Directory.Exists(m_svndir + Slash.DirectorySeparatorChar + subdir))
// Directory.CreateDirectory(m_svndir + Slash.DirectorySeparatorChar + subdir);
// m_svnClient.Checkout2(m_svnurl + "/" + subdir, m_svndir, Svn.Revision.Head, Svn.Revision.Head, true, false);
// }
// private void CheckoutSvnPartial(string subdir, SvnRevision revision)
// {
// if (!Directory.Exists(m_svndir + Slash.DirectorySeparatorChar + subdir))
// Directory.CreateDirectory(m_svndir + Slash.DirectorySeparatorChar + subdir);
// m_svnClient.Checkout2(m_svnurl + "/" + subdir, m_svndir, revision, revision, true, false);
// }
#endregion
#region SvnDotNet Callbacks
private SvnError SimpleAuth(out SvnAuthCredSimple svnCredentials, IntPtr baton,
AprString realm, AprString username, bool maySave, AprPool pool)
{
svnCredentials = SvnAuthCredSimple.Alloc(pool);
svnCredentials.Username = new AprString(m_svnuser, pool);
svnCredentials.Password = new AprString(m_svnpass, pool);
svnCredentials.MaySave = false;
return SvnError.NoError;
}
private SvnError GetCommitLogCallback(out AprString logMessage, out SvnPath tmpFile, AprArray commitItems, IntPtr baton, AprPool pool)
{
if (!commitItems.IsNull)
{
foreach (SvnClientCommitItem2 item in commitItems)
{
m_log.Debug("[SVNBACKUP]: ... " + Path.GetFileName(item.Path.ToString()) + " (" + item.Kind.ToString() + ") r" + item.Revision.ToString());
}
}
string msg = "Region Backup (" + System.Environment.MachineName + " at " + DateTime.UtcNow + " UTC)";
m_log.Debug("[SVNBACKUP]: Saved with message: " + msg);
logMessage = new AprString(msg, pool);
tmpFile = new SvnPath(pool);
return (SvnError.NoError);
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scenes = new List<Scene>();
m_timer = new Timer();
try
{
if (!source.Configs["SVN"].GetBoolean("Enabled", false))
return;
m_enabled = true;
m_svndir = source.Configs["SVN"].GetString("Directory", m_svndir);
m_svnurl = source.Configs["SVN"].GetString("URL", m_svnurl);
m_svnuser = source.Configs["SVN"].GetString("Username", m_svnuser);
m_svnpass = source.Configs["SVN"].GetString("Password", m_svnpass);
m_installBackupOnLoad = source.Configs["SVN"].GetBoolean("ImportOnStartup", m_installBackupOnLoad);
m_svnAutoSave = source.Configs["SVN"].GetBoolean("Autosave", m_svnAutoSave);
m_svnperiod = new TimeSpan(0, source.Configs["SVN"].GetInt("AutosavePeriod", (int) m_svnperiod.TotalMinutes), 0);
}
catch (Exception)
{
}
lock (m_scenes)
{
m_scenes.Add(scene);
}
//Only register it once, to prevent command being executed x*region times
if (m_scenes.Count == 1)
{
scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
}
}
public void PostInitialise()
{
if (m_enabled == false)
return;
if (m_svnAutoSave)
{
m_timer.Interval = m_svnperiod.TotalMilliseconds;
m_timer.Elapsed += m_timer_Elapsed;
m_timer.AutoReset = true;
m_timer.Start();
}
m_log.Info("[SVNBACKUP]: Connecting to SVN server " + m_svnurl + " ...");
SetupSvnProvider();
m_log.Info("[SVNBACKUP]: Creating repository in " + m_svndir + ".");
CreateSvnDirectory();
CheckoutSvn();
SetupSerialiser();
if (m_installBackupOnLoad)
{
m_log.Info("[SVNBACKUP]: Importing latest SVN revision to scenes...");
foreach (Scene scene in m_scenes)
{
LoadRegion(scene);
}
}
}
public void Close()
{
}
public string Name
{
get { return "SvnBackupModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "svn" && args[1] == "save")
{
SaveAllRegions();
}
if (args.Length == 2)
{
if (args[0] == "svn" && args[1] == "load")
{
LoadAllScenes();
}
}
if (args.Length == 3)
{
if (args[0] == "svn" && args[1] == "load")
{
LoadAllScenes(Int32.Parse(args[2]));
}
}
if (args.Length == 3)
{
if (args[0] == "svn" && args[1] == "load-region")
{
LoadScene(args[2]);
}
}
if (args.Length == 4)
{
if (args[0] == "svn" && args[1] == "load-region")
{
LoadScene(args[2], Int32.Parse(args[3]));
}
}
}
public void LoadScene(string name)
{
CheckoutSvn();
foreach (Scene scene in m_scenes)
{
if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
{
LoadRegion(scene);
return;
}
}
m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
}
public void LoadScene(string name, int revision)
{
CheckoutSvn(new SvnRevision(revision));
foreach (Scene scene in m_scenes)
{
if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
{
LoadRegion(scene);
return;
}
}
m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
}
public void LoadAllScenes()
{
CheckoutSvn();
foreach (Scene scene in m_scenes)
{
LoadRegion(scene);
}
}
public void LoadAllScenes(int revision)
{
CheckoutSvn(new SvnRevision(revision));
foreach (Scene scene in m_scenes)
{
LoadRegion(scene);
}
}
private void m_timer_Elapsed(object sender, ElapsedEventArgs e)
{
SaveAllRegions();
}
private void SetupSerialiser()
{
if (m_scenes.Count > 0)
m_serialiser = m_scenes[0].RequestModuleInterface<IRegionSerialiserModule>();
}
private void SetupSvnProvider()
{
m_svnClient = new SvnClient();
m_svnClient.AddUsernameProvider();
m_svnClient.AddPromptProvider(new SvnAuthProviderObject.SimplePrompt(SimpleAuth), IntPtr.Zero, 2);
m_svnClient.OpenAuth();
m_svnClient.Context.LogMsgFunc2 = new SvnDelegate(new SvnClient.GetCommitLog2(GetCommitLogCallback));
}
private void CreateSvnDirectory()
{
if (!Directory.Exists(m_svndir))
Directory.CreateDirectory(m_svndir);
}
}
}
| |
/*
* 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 NVelocity.Runtime.Log
{
using System;
using Exception;
/// <summary> <p>
/// This class is responsible for instantiating the correct ILogChute
/// </p>
///
/// <p>
/// The approach is :
/// </p>
/// <ul>
/// <li>
/// First try to see if the user is passing in a living object
/// that is a ILogChute, allowing the app to give its living
/// custom loggers.
/// </li>
/// <li>
/// Next, run through the (possible) list of classes specified
/// specified as loggers, taking the first one that appears to
/// work. This is how we support finding logkit, log4j or
/// jdk logging, whichever is in the classpath and found first,
/// as all three are listed as defaults.
/// </li>
/// <li>
/// Finally, we turn to the System.err stream and print Log messages
/// to it if nothing else works.
/// </li>
///
/// </summary>
/// <author> <a href="mailto:[email protected]">Jason van Zyl</a>
/// </author>
/// <author> <a href="mailto:[email protected]">Jon S. Stevens</a>
/// </author>
/// <author> <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
/// </author>
/// <author> <a href="mailto:[email protected]">Nathan Bubna</a>
/// </author>
/// <version> $Id: LogManager.java 699307 2008-09-26 13:16:05Z cbrisson $
/// </version>
public class LogManager
{
// Creates a new logging system or returns an existing one
// specified by the application.
private static ILogChute CreateLogChute(IRuntimeServices rsvc)
{
Log log = rsvc.Log;
/* If a ILogChute or LogSystem instance was set as a configuration
* value, use that. This is any class the user specifies.
*/
System.Object o = rsvc.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM);
if (o != null)
{
// first check for a ILogChute
if (o is ILogChute)
{
try
{
((ILogChute)o).Init(rsvc);
return (ILogChute)o;
}
catch (System.Exception e)
{
System.String msg = "Could not init runtime.log.logsystem " + o;
log.Error(msg, e);
throw new VelocityException(msg, e);
}
}
else
{
System.String msg = o.GetType().FullName + " object set as runtime.log.logsystem is not a valid log implementation.";
log.Error(msg);
throw new VelocityException(msg);
}
}
/* otherwise, see if a class was specified. You can Put multiple
* classes, and we use the first one we find.
*
* Note that the default value of this property contains the
* AvalonLogChute, the Log4JLogChute, CommonsLogLogChute,
* ServletLogChute, and the JdkLogChute for
* convenience - so we use whichever we works first.
*/
System.Collections.IList classes = new System.Collections.ArrayList();
System.Object obj = rsvc.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS);
/*
* we might have a list, or not - so check
*/
if (obj is System.Collections.IList)
{
classes = (System.Collections.IList)obj;
}
else if (obj is System.String)
{
classes.Add(obj);
}
/*
* now run through the list, trying each. It's ok to
* fail with a class not found, as we do this to also
* search out a default simple file logger
*/
for (System.Collections.IEnumerator ii = classes.GetEnumerator(); ii.MoveNext(); )
{
System.String claz = (System.String)ii.Current;
if (claz != null && claz.Length > 0)
{
log.Debug("Trying to use logger class " + claz);
try
{
o = Activator.CreateInstance(Type.GetType(claz.Replace(';', ',')));
if (o is ILogChute)
{
((ILogChute)o).Init(rsvc);
log.Debug("Using logger class " + claz);
return (ILogChute)o;
}
else
{
System.String msg = "The specified logger class " + claz + " does not implement the " + typeof(ILogChute).FullName + " interface.";
log.Error(msg);
// be extra informative if it appears to be a classloader issue
// this should match all our provided LogChutes
if (IsProbablyProvidedLogChute(claz))
{
// if it's likely to be ours, tip them off about classloader stuff
log.Error("This appears to be a ClassLoader issue. Check for multiple Velocity jars in your classpath.");
}
throw new VelocityException(msg);
}
}
catch (System.ApplicationException ncdfe)
{
// note these errors for anyone debugging the app
if (IsProbablyProvidedLogChute(claz))
{
log.Debug("Target log system for " + claz + " is not available (" + ncdfe.ToString() + "). Falling back to next log system...");
}
else
{
log.Debug("Couldn't find class " + claz + " or necessary supporting classes in classpath.", ncdfe);
}
}
catch (System.Exception e)
{
System.String msg = "Failed to initialize an instance of " + claz + " with the current runtime configuration.";
// Log unexpected Init exception at higher priority
log.Error(msg, e);
throw new VelocityException(msg, e);
}
}
}
/* If the above failed, that means either the user specified a
* logging class that we can't find, there weren't the necessary
* dependencies in the classpath for it, or there were the same
* problems for the default loggers, log4j and Java1.4+.
* Since we really don't know and we want to be sure the user knows
* that something went wrong with the logging, let's fall back to the
* surefire SystemLogChute. No panicking or failing to Log!!
*/
ILogChute slc = new NullLogChute();
slc.Init(rsvc);
log.Debug("Using SystemLogChute.");
return slc;
}
/// <summary> Simply tells whether the specified classname probably is provided
/// by Velocity or is implemented by someone else. Not surefire, but
/// it'll probably always be right. In any case, this method shouldn't
/// be relied upon for anything important.
/// </summary>
private static bool IsProbablyProvidedLogChute(System.String claz)
{
if (claz == null)
{
return false;
}
else
{
return (claz.StartsWith("org.apache.velocity.runtime.log") && claz.EndsWith("ILogChute"));
}
}
/// <summary> Update the Log instance with the appropriate ILogChute and other
/// settings determined by the RuntimeServices.
/// </summary>
/// <param name="Log">
/// </param>
/// <param name="rsvc">
/// </param>
/// <throws> Exception </throws>
/// <since> 1.5
/// </since>
public static void UpdateLog(Log log, IRuntimeServices rsvc)
{
// create a new ILogChute using the RuntimeServices
ILogChute newLogChute = CreateLogChute(rsvc);
ILogChute oldLogChute = log.GetLogChute();
// pass the new ILogChute to the Log first,
// (if the old was a HoldingLogChute, we don't want it
// to accrue new messages during the transfer below)
log.SetLogChute(newLogChute);
// If the old ILogChute was the pre-Init logger,
// dump its messages into the new system.
if (oldLogChute is HoldingLogChute)
{
HoldingLogChute hlc = (HoldingLogChute)oldLogChute;
hlc.TransferTo(newLogChute);
}
}
}
}
| |
// Copyright 2017 The Draco 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.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
public unsafe class DracoMeshLoader
{
// These values must be exactly the same as the values in draco_types.h.
// Attribute data type.
enum DataType {
DT_INVALID = 0,
DT_INT8,
DT_UINT8,
DT_INT16,
DT_UINT16,
DT_INT32,
DT_UINT32,
DT_INT64,
DT_UINT64,
DT_FLOAT32,
DT_FLOAT64,
DT_BOOL
};
// These values must be exactly the same as the values in
// geometry_attribute.h.
// Attribute type.
enum AttributeType {
INVALID = -1,
POSITION = 0,
NORMAL,
COLOR,
TEX_COORD,
// A special id used to mark attributes that are not assigned to any known
// predefined use case. Such attributes are often used for a shader specific
// data.
GENERIC
};
// The order must be consistent with C++ interface.
[StructLayout (LayoutKind.Sequential)] public struct DracoData
{
public int dataType;
public IntPtr data;
}
[StructLayout (LayoutKind.Sequential)] public struct DracoAttribute
{
public int attributeType;
public int dataType;
public int numComponents;
public int uniqueId;
}
[StructLayout (LayoutKind.Sequential)] public struct DracoMesh
{
public int numFaces;
public int numVertices;
public int numAttributes;
}
// Release data associated with DracoMesh.
[DllImport ("dracodec_unity")] private static extern void ReleaseDracoMesh(
DracoMesh**mesh);
// Release data associated with DracoAttribute.
[DllImport ("dracodec_unity")] private static extern void
ReleaseDracoAttribute(DracoAttribute**attr);
// Release attribute data.
[DllImport ("dracodec_unity")] private static extern void ReleaseDracoData(
DracoData**data);
// Decodes compressed Draco::Mesh in buffer to mesh. On input, mesh
// must be null. The returned mesh must released with ReleaseDracoMesh.
[DllImport ("dracodec_unity")] private static extern int DecodeDracoMesh(
byte[] buffer, int length, DracoMesh**mesh);
// Returns the DracoAttribute at index in mesh. On input, attribute must be
// null. The returned attr must be released with ReleaseDracoAttribute.
[DllImport ("dracodec_unity")] private static extern bool GetAttribute(
DracoMesh* mesh, int index, DracoAttribute**attr);
// Returns the DracoAttribute of type at index in mesh. On input, attribute
// must be null. E.g. If the mesh has two texture coordinates then
// GetAttributeByType(mesh, AttributeType.TEX_COORD, 1, &attr); will return
// the second TEX_COORD attribute. The returned attr must be released with
// ReleaseDracoAttribute.
[DllImport ("dracodec_unity")] private static extern bool GetAttributeByType(
DracoMesh* mesh, AttributeType type, int index, DracoAttribute**attr);
// Returns the DracoAttribute with unique_id in mesh. On input, attribute
// must be null.The returned attr must be released with
// ReleaseDracoAttribute.
[DllImport ("dracodec_unity")] private static extern bool
GetAttributeByUniqueId(DracoMesh* mesh, int unique_id,
DracoAttribute**attr);
// Returns an array of indices as well as the type of data in data_type. On
// input, indices must be null. The returned indices must be released with
// ReleaseDracoData.
[DllImport ("dracodec_unity")] private static extern bool GetMeshIndices(
DracoMesh* mesh, DracoData**indices);
// Returns an array of attribute data as well as the type of data in
// data_type. On input, data must be null. The returned data must be
// released with ReleaseDracoData.
[DllImport ("dracodec_unity")] private static extern bool GetAttributeData(
DracoMesh* mesh, DracoAttribute* attr, DracoData**data);
public int LoadMeshFromAsset(string assetName, ref List<Mesh> meshes)
{
TextAsset asset =
Resources.Load(assetName, typeof(TextAsset)) as TextAsset;
if (asset == null) {
Debug.Log ("Didn't load file!");
return -1;
}
byte[] encodedData = asset.bytes;
Debug.Log(encodedData.Length.ToString());
if (encodedData.Length == 0) {
Debug.Log ("Didn't load encoded data!");
return -1;
}
return ConvertDracoMeshToUnity(encodedData, ref meshes);
}
// Decodes a Draco mesh, creates a Unity mesh from the decoded data and
// adds the Unity mesh to meshes. encodedData is the compressed Draco mesh.
public unsafe int ConvertDracoMeshToUnity(byte[] encodedData,
ref List<Mesh> meshes)
{
float startTime = Time.realtimeSinceStartup;
DracoMesh *mesh = null;
if (DecodeDracoMesh(encodedData, encodedData.Length, &mesh) <= 0) {
Debug.Log("Failed: Decoding error.");
return -1;
}
float decodeTimeMilli =
(Time.realtimeSinceStartup - startTime) * 1000.0f;
Debug.Log("decodeTimeMilli: " + decodeTimeMilli.ToString());
Debug.Log("Num indices: " + mesh->numFaces.ToString());
Debug.Log("Num vertices: " + mesh->numVertices.ToString());
Debug.Log("Num attributes: " + mesh->numAttributes.ToString());
Mesh unityMesh = CreateUnityMesh(mesh);
UnityMeshToCamera(ref unityMesh);
meshes.Add(unityMesh);
int numFaces = mesh->numFaces;
ReleaseDracoMesh(&mesh);
return numFaces;
}
// Creates a Unity mesh from the decoded Draco mesh.
public unsafe Mesh CreateUnityMesh(DracoMesh *dracoMesh)
{
float startTime = Time.realtimeSinceStartup;
int numFaces = dracoMesh->numFaces;
int[] newTriangles = new int[dracoMesh->numFaces * 3];
Vector3[] newVertices = new Vector3[dracoMesh->numVertices];
Vector2[] newUVs = null;
Vector3[] newNormals = null;
Color[] newColors = null;
byte[] newGenerics = null;
// Copy face indices.
DracoData *indicesData;
GetMeshIndices(dracoMesh, &indicesData);
int elementSize =
DataTypeSize((DracoMeshLoader.DataType)indicesData->dataType);
int *indices = (int*)(indicesData->data);
var indicesPtr = UnsafeUtility.AddressOf(ref newTriangles[0]);
UnsafeUtility.MemCpy(indicesPtr, indices,
newTriangles.Length * elementSize);
ReleaseDracoData(&indicesData);
// Copy positions.
DracoAttribute *attr = null;
GetAttributeByType(dracoMesh, AttributeType.POSITION, 0, &attr);
DracoData* posData = null;
GetAttributeData(dracoMesh, attr, &posData);
elementSize = DataTypeSize((DracoMeshLoader.DataType)posData->dataType) *
attr->numComponents;
var newVerticesPtr = UnsafeUtility.AddressOf(ref newVertices[0]);
UnsafeUtility.MemCpy(newVerticesPtr, (void*)posData->data,
dracoMesh->numVertices * elementSize);
ReleaseDracoData(&posData);
ReleaseDracoAttribute(&attr);
// Copy normals.
if (GetAttributeByType(dracoMesh, AttributeType.NORMAL, 0, &attr)) {
DracoData* normData = null;
if (GetAttributeData(dracoMesh, attr, &normData)) {
elementSize =
DataTypeSize((DracoMeshLoader.DataType)normData->dataType) *
attr->numComponents;
newNormals = new Vector3[dracoMesh->numVertices];
var newNormalsPtr = UnsafeUtility.AddressOf(ref newNormals[0]);
UnsafeUtility.MemCpy(newNormalsPtr, (void*)normData->data,
dracoMesh->numVertices * elementSize);
Debug.Log("Decoded mesh normals.");
ReleaseDracoData(&normData);
ReleaseDracoAttribute(&attr);
}
}
// Copy texture coordinates.
if (GetAttributeByType(dracoMesh, AttributeType.TEX_COORD, 0, &attr)) {
DracoData* texData = null;
if (GetAttributeData(dracoMesh, attr, &texData)) {
elementSize =
DataTypeSize((DracoMeshLoader.DataType)texData->dataType) *
attr->numComponents;
newUVs = new Vector2[dracoMesh->numVertices];
var newUVsPtr = UnsafeUtility.AddressOf(ref newUVs[0]);
UnsafeUtility.MemCpy(newUVsPtr, (void*)texData->data,
dracoMesh->numVertices * elementSize);
Debug.Log("Decoded mesh texcoords.");
ReleaseDracoData(&texData);
ReleaseDracoAttribute(&attr);
}
}
// Copy colors.
if (GetAttributeByType(dracoMesh, AttributeType.COLOR, 0, &attr)) {
DracoData* colorData = null;
if (GetAttributeData(dracoMesh, attr, &colorData)) {
elementSize =
DataTypeSize((DracoMeshLoader.DataType)colorData->dataType) *
attr->numComponents;
newColors = new Color[dracoMesh->numVertices];
var newColorsPtr = UnsafeUtility.AddressOf(ref newColors[0]);
UnsafeUtility.MemCpy(newColorsPtr, (void*)colorData->data,
dracoMesh->numVertices * elementSize);
Debug.Log("Decoded mesh colors.");
ReleaseDracoData(&colorData);
ReleaseDracoAttribute(&attr);
}
}
// Copy generic data. This script does not do anyhting with the generic
// data.
if (GetAttributeByType(dracoMesh, AttributeType.GENERIC, 0, &attr)) {
DracoData* genericData = null;
if (GetAttributeData(dracoMesh, attr, &genericData)) {
elementSize =
DataTypeSize((DracoMeshLoader.DataType)genericData->dataType) *
attr->numComponents;
newGenerics = new byte[dracoMesh->numVertices * elementSize];
var newGenericPtr = UnsafeUtility.AddressOf(ref newGenerics[0]);
UnsafeUtility.MemCpy(newGenericPtr, (void*)genericData->data,
dracoMesh->numVertices * elementSize);
Debug.Log("Decoded mesh generic data.");
ReleaseDracoData(&genericData);
ReleaseDracoAttribute(&attr);
}
}
float copyDecodedDataTimeMilli =
(Time.realtimeSinceStartup - startTime) * 1000.0f;
Debug.Log("copyDecodedDataTimeMilli: " +
copyDecodedDataTimeMilli.ToString());
startTime = Time.realtimeSinceStartup;
Mesh mesh = new Mesh();
#if UNITY_2017_3_OR_NEWER
mesh.indexFormat = (newVertices.Length > System.UInt16.MaxValue)
? UnityEngine.Rendering.IndexFormat.UInt32
: UnityEngine.Rendering.IndexFormat.UInt16;
#else
if (newVertices.Length > System.UInt16.MaxValue) {
throw new System.Exception("Draco meshes with more than 65535 vertices are only supported from Unity 2017.3 onwards.");
}
#endif
mesh.vertices = newVertices;
mesh.SetTriangles(newTriangles, 0, true);
if (newUVs != null) {
mesh.uv = newUVs;
}
if (newNormals != null) {
mesh.normals = newNormals;
} else {
mesh.RecalculateNormals();
Debug.Log("Mesh doesn't have normals, recomputed.");
}
if (newColors != null) {
mesh.colors = newColors;
}
float convertTimeMilli =
(Time.realtimeSinceStartup - startTime) * 1000.0f;
Debug.Log("convertTimeMilli: " + convertTimeMilli.ToString());
return mesh;
}
// Scale and translate the decoded mesh so it will be visible to
// a new camera's default settings.
public unsafe void UnityMeshToCamera(ref Mesh mesh)
{
float startTime = Time.realtimeSinceStartup;
mesh.RecalculateBounds();
float scale = 0.5f / mesh.bounds.extents.x;
if (0.5f / mesh.bounds.extents.y < scale) {
scale = 0.5f / mesh.bounds.extents.y;
}
if (0.5f / mesh.bounds.extents.z < scale) {
scale = 0.5f / mesh.bounds.extents.z;
}
Vector3[] vertices = mesh.vertices;
int i = 0;
while (i < vertices.Length) {
vertices[i] *= scale;
i++;
}
mesh.vertices = vertices;
mesh.RecalculateBounds();
Vector3 translate = mesh.bounds.center;
translate.x = 0 - mesh.bounds.center.x;
translate.y = 0 - mesh.bounds.center.y;
translate.z = 2 - mesh.bounds.center.z;
i = 0;
while (i < vertices.Length) {
vertices[i] += translate;
i++;
}
mesh.vertices = vertices;
float transformTimeMilli =
(Time.realtimeSinceStartup - startTime) * 1000.0f;
Debug.Log("transformTimeMilli: " + transformTimeMilli.ToString());
}
private int DataTypeSize(DataType dt) {
switch (dt) {
case DataType.DT_INT8:
case DataType.DT_UINT8:
return 1;
case DataType.DT_INT16:
case DataType.DT_UINT16:
return 2;
case DataType.DT_INT32:
case DataType.DT_UINT32:
return 4;
case DataType.DT_INT64:
case DataType.DT_UINT64:
return 8;
case DataType.DT_FLOAT32:
return 4;
case DataType.DT_FLOAT64:
return 8;
case DataType.DT_BOOL:
return 1;
default:
return -1;
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// System.Globalization.StringInfo.GetTestElementEnumerator(string,Int32)
/// </summary>
public class StringInfoGetTextElementEnumerator2
{
private const int c_MINI_STRING_LENGTH = 8;
private const int c_MAX_STRING_LENGTH = 256;
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The argument is a random string,and start at a random index");
try
{
string str = TestLibrary.Generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int len = str.Length;
int index = this.GetInt32(8, len);
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, index);
TextElementEnumerator.MoveNext();
for (int i = 0; i < len - index; i++)
{
if (TextElementEnumerator.Current.ToString() != str[i + index].ToString())
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,the str is: " + str[i + index]);
retVal = false;
}
TextElementEnumerator.MoveNext();
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The string has a surrogate pair");
try
{
string str = "\uDBFF\uDFFF";
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("s\uDBFF\uDFFF$", 1);
TextElementEnumerator.MoveNext();
if (TextElementEnumerator.Current.ToString() != str)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
retVal = false;
}
TextElementEnumerator.MoveNext();
if (TextElementEnumerator.Current.ToString() != "$")
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The string has a combining character");
try
{
string str = "a\u20D1";
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("13229^a\u20D1a", 6);
TextElementEnumerator.MoveNext();
if (TextElementEnumerator.Current.ToString() != str)
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
retVal = false;
}
TextElementEnumerator.MoveNext();
if (TextElementEnumerator.Current.ToString() != "a")
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
retVal = false;
}
if (TextElementEnumerator.MoveNext())
{
TestLibrary.TestFramework.LogError("008", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The string is a null reference");
try
{
string str = null;
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, 0);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The index is out of the range of the string");
try
{
string str = "dur8&p!";
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, 10);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The index is a negative number");
try
{
string str = "dur8&p!";
TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, -10);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
StringInfoGetTextElementEnumerator2 test = new StringInfoGetTextElementEnumerator2();
TestLibrary.TestFramework.BeginTestCase("StringInfoGetTextElementEnumerator2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
| |
using System;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Digests
{
/**
* implementation of RipeMD see,
* http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
*/
internal class RipeMD160Digest
: GeneralDigest
{
private const int DigestLength = 20;
private int H0, H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public RipeMD160Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public RipeMD160Digest(RipeMD160Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(RipeMD160Digest t)
{
base.CopyIn(t);
H0 = t.H0;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get
{
return "RIPEMD160";
}
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)((ulong)bitLength >> 32);
}
private void UnpackWord(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)word;
outBytes[outOff + 1] = (byte)((uint)word >> 8);
outBytes[outOff + 2] = (byte)((uint)word >> 16);
outBytes[outOff + 3] = (byte)((uint)word >> 24);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
UnpackWord(H0, output, outOff);
UnpackWord(H1, output, outOff + 4);
UnpackWord(H2, output, outOff + 8);
UnpackWord(H3, output, outOff + 12);
UnpackWord(H4, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables to the IV values.
*/
public override void Reset()
{
base.Reset();
H0 = unchecked((int)0x67452301);
H1 = unchecked((int)0xefcdab89);
H2 = unchecked((int)0x98badcfe);
H3 = unchecked((int)0x10325476);
H4 = unchecked((int)0xc3d2e1f0);
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
/*
* rotate int x left n bits.
*/
private int RL(
int x,
int n)
{
return (x << n) | (int)((uint)x >> (32 - n));
}
/*
* f1,f2,f3,f4,f5 are the basic RipeMD160 functions.
*/
/*
* rounds 0-15
*/
private int F1(
int x,
int y,
int z)
{
return x ^ y ^ z;
}
/*
* rounds 16-31
*/
private int F2(
int x,
int y,
int z)
{
return (x & y) | (~x & z);
}
/*
* rounds 32-47
*/
private int F3(
int x,
int y,
int z)
{
return (x | ~y) ^ z;
}
/*
* rounds 48-63
*/
private int F4(
int x,
int y,
int z)
{
return (x & z) | (y & ~z);
}
/*
* rounds 64-79
*/
private int F5(
int x,
int y,
int z)
{
return x ^ (y | ~z);
}
internal override void ProcessBlock()
{
int a, aa;
int b, bb;
int c, cc;
int d, dd;
int e, ee;
a = aa = H0;
b = bb = H1;
c = cc = H2;
d = dd = H3;
e = ee = H4;
//
// Rounds 1 - 16
//
// left
a = RL(a + F1(b, c, d) + X[0], 11) + e;
c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[1], 14) + d;
b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[2], 15) + c;
a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[3], 12) + b;
e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[4], 5) + a;
d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[5], 8) + e;
c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[6], 7) + d;
b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[7], 9) + c;
a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[8], 11) + b;
e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[9], 13) + a;
d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[10], 14) + e;
c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[11], 15) + d;
b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[12], 6) + c;
a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[13], 7) + b;
e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[14], 9) + a;
d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[15], 8) + e;
c = RL(c, 10);
// right
aa = RL(aa + F5(bb, cc, dd) + X[5] + unchecked((int)0x50a28be6), 8) + ee;
cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[14] + unchecked((int)0x50a28be6), 9) + dd;
bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[7] + unchecked((int)0x50a28be6), 9) + cc;
aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[0] + unchecked((int)0x50a28be6), 11) + bb;
ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[9] + unchecked((int)0x50a28be6), 13) + aa;
dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[2] + unchecked((int)0x50a28be6), 15) + ee;
cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[11] + unchecked((int)0x50a28be6), 15) + dd;
bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[4] + unchecked((int)0x50a28be6), 5) + cc;
aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[13] + unchecked((int)0x50a28be6), 7) + bb;
ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[6] + unchecked((int)0x50a28be6), 7) + aa;
dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[15] + unchecked((int)0x50a28be6), 8) + ee;
cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[8] + unchecked((int)0x50a28be6), 11) + dd;
bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[1] + unchecked((int)0x50a28be6), 14) + cc;
aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[10] + unchecked((int)0x50a28be6), 14) + bb;
ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[3] + unchecked((int)0x50a28be6), 12) + aa;
dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[12] + unchecked((int)0x50a28be6), 6) + ee;
cc = RL(cc, 10);
//
// Rounds 16-31
//
// left
e = RL(e + F2(a, b, c) + X[7] + unchecked((int)0x5a827999), 7) + d;
b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[4] + unchecked((int)0x5a827999), 6) + c;
a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[13] + unchecked((int)0x5a827999), 8) + b;
e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[1] + unchecked((int)0x5a827999), 13) + a;
d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[10] + unchecked((int)0x5a827999), 11) + e;
c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[6] + unchecked((int)0x5a827999), 9) + d;
b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[15] + unchecked((int)0x5a827999), 7) + c;
a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[3] + unchecked((int)0x5a827999), 15) + b;
e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[12] + unchecked((int)0x5a827999), 7) + a;
d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[0] + unchecked((int)0x5a827999), 12) + e;
c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[9] + unchecked((int)0x5a827999), 15) + d;
b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[5] + unchecked((int)0x5a827999), 9) + c;
a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[2] + unchecked((int)0x5a827999), 11) + b;
e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[14] + unchecked((int)0x5a827999), 7) + a;
d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[11] + unchecked((int)0x5a827999), 13) + e;
c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[8] + unchecked((int)0x5a827999), 12) + d;
b = RL(b, 10);
// right
ee = RL(ee + F4(aa, bb, cc) + X[6] + unchecked((int)0x5c4dd124), 9) + dd;
bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[11] + unchecked((int)0x5c4dd124), 13) + cc;
aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[3] + unchecked((int)0x5c4dd124), 15) + bb;
ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[7] + unchecked((int)0x5c4dd124), 7) + aa;
dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[0] + unchecked((int)0x5c4dd124), 12) + ee;
cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[13] + unchecked((int)0x5c4dd124), 8) + dd;
bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[5] + unchecked((int)0x5c4dd124), 9) + cc;
aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[10] + unchecked((int)0x5c4dd124), 11) + bb;
ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[14] + unchecked((int)0x5c4dd124), 7) + aa;
dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[15] + unchecked((int)0x5c4dd124), 7) + ee;
cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[8] + unchecked((int)0x5c4dd124), 12) + dd;
bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[12] + unchecked((int)0x5c4dd124), 7) + cc;
aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[4] + unchecked((int)0x5c4dd124), 6) + bb;
ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[9] + unchecked((int)0x5c4dd124), 15) + aa;
dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[1] + unchecked((int)0x5c4dd124), 13) + ee;
cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[2] + unchecked((int)0x5c4dd124), 11) + dd;
bb = RL(bb, 10);
//
// Rounds 32-47
//
// left
d = RL(d + F3(e, a, b) + X[3] + unchecked((int)0x6ed9eba1), 11) + c;
a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[10] + unchecked((int)0x6ed9eba1), 13) + b;
e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[14] + unchecked((int)0x6ed9eba1), 6) + a;
d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[4] + unchecked((int)0x6ed9eba1), 7) + e;
c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[9] + unchecked((int)0x6ed9eba1), 14) + d;
b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[15] + unchecked((int)0x6ed9eba1), 9) + c;
a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[8] + unchecked((int)0x6ed9eba1), 13) + b;
e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[1] + unchecked((int)0x6ed9eba1), 15) + a;
d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[2] + unchecked((int)0x6ed9eba1), 14) + e;
c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[7] + unchecked((int)0x6ed9eba1), 8) + d;
b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[0] + unchecked((int)0x6ed9eba1), 13) + c;
a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[6] + unchecked((int)0x6ed9eba1), 6) + b;
e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[13] + unchecked((int)0x6ed9eba1), 5) + a;
d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[11] + unchecked((int)0x6ed9eba1), 12) + e;
c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[5] + unchecked((int)0x6ed9eba1), 7) + d;
b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[12] + unchecked((int)0x6ed9eba1), 5) + c;
a = RL(a, 10);
// right
dd = RL(dd + F3(ee, aa, bb) + X[15] + unchecked((int)0x6d703ef3), 9) + cc;
aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[5] + unchecked((int)0x6d703ef3), 7) + bb;
ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[1] + unchecked((int)0x6d703ef3), 15) + aa;
dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[3] + unchecked((int)0x6d703ef3), 11) + ee;
cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[7] + unchecked((int)0x6d703ef3), 8) + dd;
bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[14] + unchecked((int)0x6d703ef3), 6) + cc;
aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[6] + unchecked((int)0x6d703ef3), 6) + bb;
ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[9] + unchecked((int)0x6d703ef3), 14) + aa;
dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[11] + unchecked((int)0x6d703ef3), 12) + ee;
cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[8] + unchecked((int)0x6d703ef3), 13) + dd;
bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[12] + unchecked((int)0x6d703ef3), 5) + cc;
aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[2] + unchecked((int)0x6d703ef3), 14) + bb;
ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[10] + unchecked((int)0x6d703ef3), 13) + aa;
dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[0] + unchecked((int)0x6d703ef3), 13) + ee;
cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[4] + unchecked((int)0x6d703ef3), 7) + dd;
bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[13] + unchecked((int)0x6d703ef3), 5) + cc;
aa = RL(aa, 10);
//
// Rounds 48-63
//
// left
c = RL(c + F4(d, e, a) + X[1] + unchecked((int)0x8f1bbcdc), 11) + b;
e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[9] + unchecked((int)0x8f1bbcdc), 12) + a;
d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[11] + unchecked((int)0x8f1bbcdc), 14) + e;
c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[10] + unchecked((int)0x8f1bbcdc), 15) + d;
b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[0] + unchecked((int)0x8f1bbcdc), 14) + c;
a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[8] + unchecked((int)0x8f1bbcdc), 15) + b;
e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[12] + unchecked((int)0x8f1bbcdc), 9) + a;
d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[4] + unchecked((int)0x8f1bbcdc), 8) + e;
c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[13] + unchecked((int)0x8f1bbcdc), 9) + d;
b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[3] + unchecked((int)0x8f1bbcdc), 14) + c;
a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[7] + unchecked((int)0x8f1bbcdc), 5) + b;
e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[15] + unchecked((int)0x8f1bbcdc), 6) + a;
d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[14] + unchecked((int)0x8f1bbcdc), 8) + e;
c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[5] + unchecked((int)0x8f1bbcdc), 6) + d;
b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[6] + unchecked((int)0x8f1bbcdc), 5) + c;
a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[2] + unchecked((int)0x8f1bbcdc), 12) + b;
e = RL(e, 10);
// right
cc = RL(cc + F2(dd, ee, aa) + X[8] + unchecked((int)0x7a6d76e9), 15) + bb;
ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[6] + unchecked((int)0x7a6d76e9), 5) + aa;
dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[4] + unchecked((int)0x7a6d76e9), 8) + ee;
cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[1] + unchecked((int)0x7a6d76e9), 11) + dd;
bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[3] + unchecked((int)0x7a6d76e9), 14) + cc;
aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[11] + unchecked((int)0x7a6d76e9), 14) + bb;
ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[15] + unchecked((int)0x7a6d76e9), 6) + aa;
dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[0] + unchecked((int)0x7a6d76e9), 14) + ee;
cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[5] + unchecked((int)0x7a6d76e9), 6) + dd;
bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[12] + unchecked((int)0x7a6d76e9), 9) + cc;
aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[2] + unchecked((int)0x7a6d76e9), 12) + bb;
ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[13] + unchecked((int)0x7a6d76e9), 9) + aa;
dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[9] + unchecked((int)0x7a6d76e9), 12) + ee;
cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[7] + unchecked((int)0x7a6d76e9), 5) + dd;
bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[10] + unchecked((int)0x7a6d76e9), 15) + cc;
aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[14] + unchecked((int)0x7a6d76e9), 8) + bb;
ee = RL(ee, 10);
//
// Rounds 64-79
//
// left
b = RL(b + F5(c, d, e) + X[4] + unchecked((int)0xa953fd4e), 9) + a;
d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[0] + unchecked((int)0xa953fd4e), 15) + e;
c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[5] + unchecked((int)0xa953fd4e), 5) + d;
b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[9] + unchecked((int)0xa953fd4e), 11) + c;
a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[7] + unchecked((int)0xa953fd4e), 6) + b;
e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[12] + unchecked((int)0xa953fd4e), 8) + a;
d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[2] + unchecked((int)0xa953fd4e), 13) + e;
c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[10] + unchecked((int)0xa953fd4e), 12) + d;
b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[14] + unchecked((int)0xa953fd4e), 5) + c;
a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[1] + unchecked((int)0xa953fd4e), 12) + b;
e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[3] + unchecked((int)0xa953fd4e), 13) + a;
d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[8] + unchecked((int)0xa953fd4e), 14) + e;
c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[11] + unchecked((int)0xa953fd4e), 11) + d;
b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[6] + unchecked((int)0xa953fd4e), 8) + c;
a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[15] + unchecked((int)0xa953fd4e), 5) + b;
e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[13] + unchecked((int)0xa953fd4e), 6) + a;
d = RL(d, 10);
// right
bb = RL(bb + F1(cc, dd, ee) + X[12], 8) + aa;
dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[15], 5) + ee;
cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[10], 12) + dd;
bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[4], 9) + cc;
aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[1], 12) + bb;
ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[5], 5) + aa;
dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[8], 14) + ee;
cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[7], 6) + dd;
bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[6], 8) + cc;
aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[2], 13) + bb;
ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[13], 6) + aa;
dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[14], 5) + ee;
cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[0], 15) + dd;
bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[3], 13) + cc;
aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[9], 11) + bb;
ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[11], 11) + aa;
dd = RL(dd, 10);
dd += c + H1;
H1 = H2 + d + ee;
H2 = H3 + e + aa;
H3 = H4 + a + bb;
H4 = H0 + b + cc;
H0 = dd;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
#if !NO_BC
public override IMemoable Copy()
{
return new RipeMD160Digest(this);
}
public override void Reset(IMemoable other)
{
RipeMD160Digest d = (RipeMD160Digest)other;
CopyIn(d);
}
#endif
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Deletes the specified authorization from the specified express
/// route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an authorization in the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified authorization from the specified express
/// route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an authorization in the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: UIElementParagraph class provides a wrapper for UIElements.
//
//---------------------------------------------------------------------------
#pragma warning disable 1634, 1691 // avoid generating warnings about unknown
// message numbers and unknown pragmas for PRESharp contol
using System;
using System.Collections; // IEnumerator
using System.Security; // SecurityCritical
using System.Windows; // UIElement
using System.Windows.Documents; // BlockUIContainer
using MS.Internal.Text; // TextDpi
using MS.Internal.Documents; // UIElementIsland
using MS.Internal.PtsHost.UnsafeNativeMethods; // PTS
namespace MS.Internal.PtsHost
{
/// <summary>
/// UIElementParagraph class provides a wrapper for UIElement objects.
/// </summary>
internal sealed class UIElementParagraph : FloaterBaseParagraph
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="element">Element associated with paragraph.</param>
/// <param name="structuralCache">Content's structural cache.</param>
internal UIElementParagraph(TextElement element, StructuralCache structuralCache)
: base(element, structuralCache)
{
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Dispose the object and release handle.
/// </summary>
public override void Dispose()
{
ClearUIElementIsland();
base.Dispose();
}
/// <summary>
/// Invalidate content's structural cache. Returns: 'true' if entire paragraph
/// is invalid.
/// </summary>
/// <param name="startPosition">
/// Position to start invalidation from.
/// </param>
internal override bool InvalidateStructure(int startPosition)
{
if (_uiElementIsland != null)
{
_uiElementIsland.DesiredSizeChanged -= new DesiredSizeChangedEventHandler(OnUIElementDesiredSizeChanged);
_uiElementIsland.Dispose();
_uiElementIsland = null;
}
return base.InvalidateStructure(startPosition);
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// PTS callbacks
//
//-------------------------------------------------------------------
#region PTS callbacks
//-------------------------------------------------------------------
// CreateParaclient
//-------------------------------------------------------------------
internal override void CreateParaclient(
out IntPtr paraClientHandle) // OUT: opaque to PTS paragraph client
{
#pragma warning disable 6518
// Disable PRESharp warning 6518. FloaterParaClient is an UnmamangedHandle, that adds itself
// to HandleMapper that holds a reference to it. PTS manages lifetime of this object, and
// calls DestroyParaclient to get rid of it. DestroyParaclient will call Dispose() on the object
// and remove it from HandleMapper.
UIElementParaClient paraClient = new UIElementParaClient(this);
paraClientHandle = paraClient.Handle;
#pragma warning restore 6518
}
//-------------------------------------------------------------------
// CollapseMargin
//-------------------------------------------------------------------
internal override void CollapseMargin(
BaseParaClient paraClient, // IN:
MarginCollapsingState mcs, // IN: input margin collapsing state
uint fswdir, // IN: current direction (of the track, in which margin collapsing is happening)
bool suppressTopSpace, // IN: suppress empty space at the top of page
out int dvr) // OUT: dvr, calculated based on margin collapsing state
{
MbpInfo mbp = MbpInfo.FromElement(Element);
MarginCollapsingState mcsNew;
int margin;
MarginCollapsingState.CollapseTopMargin(PtsContext, mbp, mcs, out mcsNew, out margin);
if (suppressTopSpace)
{
dvr = 0;
}
else
{
dvr = margin;
if (mcsNew != null)
{
dvr += mcsNew.Margin;
}
}
if (mcsNew != null)
{
mcsNew.Dispose();
}
}
//-------------------------------------------------------------------
// GetFloaterProperties
//-------------------------------------------------------------------
internal override void GetFloaterProperties(
uint fswdirTrack, // IN: direction of track
out PTS.FSFLOATERPROPS fsfloaterprops) // OUT: properties of the floater
{
fsfloaterprops = new PTS.FSFLOATERPROPS();
fsfloaterprops.fFloat = PTS.False; // Floater
fsfloaterprops.fskclear = PTS.WrapDirectionToFskclear((WrapDirection)Element.GetValue(Block.ClearFloatersProperty));
// Set alignment to left alignment. Do not allow text wrap on any side
fsfloaterprops.fskfloatalignment = PTS.FSKFLOATALIGNMENT.fskfloatalignMin;
fsfloaterprops.fskwr = PTS.FSKWRAP.fskwrNone;
// Always delay UIElement if there is no progress
fsfloaterprops.fDelayNoProgress = PTS.True;
}
//-------------------------------------------------------------------
// FormatFloaterContentFinite
//-------------------------------------------------------------------
internal override void FormatFloaterContentFinite(
FloaterBaseParaClient paraClient, // IN:
IntPtr pbrkrecIn, // IN: break record---use if !IntPtr.Zero
int fBRFromPreviousPage, // IN: break record was created on previous page
IntPtr footnoteRejector, // IN:
int fEmptyOk, // IN: is it OK not to add anything?
int fSuppressTopSpace, // IN: suppress empty space at the top of the page
uint fswdir, // IN: direction of Track
int fAtMaxWidth, // IN: formating is at full width of column
int durAvailable, // IN: width of available space
int dvrAvailable, // IN: height of available space
PTS.FSKSUPPRESSHARDBREAKBEFOREFIRSTPARA fsksuppresshardbreakbeforefirstparaIn,
// IN: suppress breaks at track start?
out PTS.FSFMTR fsfmtr, // OUT: result of formatting
out IntPtr pfsFloatContent, // OUT: opaque for PTS pointer pointer to formatted content
out IntPtr pbrkrecOut, // OUT: pointer to the floater content break record
out int durFloaterWidth, // OUT: floater width
out int dvrFloaterHeight, // OUT: floater height
out PTS.FSBBOX fsbbox, // OUT: floater bbox
out int cPolygons, // OUT: number of polygons
out int cVertices) // OUT: total number of vertices in all polygons
{
Invariant.Assert(paraClient is UIElementParaClient);
Invariant.Assert(Element is BlockUIContainer);
if (fAtMaxWidth == PTS.False && fEmptyOk == PTS.True)
{
// Do not format if not at max width, and if fEmptyOk is true
durFloaterWidth = dvrFloaterHeight = 0;
cPolygons = cVertices = 0;
fsfmtr = new PTS.FSFMTR();
fsfmtr.kstop = PTS.FSFMTRKSTOP.fmtrNoProgressOutOfSpace;
fsfmtr.fContainsItemThatStoppedBeforeFootnote = PTS.False;
fsfmtr.fForcedProgress = PTS.False;
fsbbox = new PTS.FSBBOX();
fsbbox.fDefined = PTS.False;
pbrkrecOut = IntPtr.Zero;
pfsFloatContent = IntPtr.Zero;
}
else
{
cPolygons = cVertices = 0;
// Formatting is not at max width but proceeds anyway because adding no content is not allowed
fsfmtr.fForcedProgress = PTS.FromBoolean(fAtMaxWidth == PTS.False);
// Format UIElement
if (((BlockUIContainer)Element).Child != null)
{
EnsureUIElementIsland();
FormatUIElement(durAvailable, out fsbbox);
}
else
{
// Child elementis null. Create fsbbox only with border and padding info
ClearUIElementIsland();
MbpInfo mbp = MbpInfo.FromElement(Element);
fsbbox.fsrc = new PTS.FSRECT();
fsbbox.fsrc.du = durAvailable;
fsbbox.fsrc.dv = mbp.BPTop + mbp.BPBottom;
}
durFloaterWidth = fsbbox.fsrc.du;
dvrFloaterHeight = fsbbox.fsrc.dv;
if (dvrAvailable < dvrFloaterHeight && fEmptyOk == PTS.True)
{
// Will not fit in available space. Since fEmptyOk is true, we can return null floater
durFloaterWidth = dvrFloaterHeight = 0;
fsfmtr = new PTS.FSFMTR();
fsfmtr.kstop = PTS.FSFMTRKSTOP.fmtrNoProgressOutOfSpace;
fsbbox = new PTS.FSBBOX();
fsbbox.fDefined = PTS.False;
pfsFloatContent = IntPtr.Zero;
}
else
{
// Either floater fits in available space or it doesn't but we cannot return nothing.
// Use the space needed, and set formatter result to forced progress if BUC does not fit in available space.
fsbbox.fDefined = PTS.True;
pfsFloatContent = paraClient.Handle;
if (dvrAvailable < dvrFloaterHeight)
{
// Indicate that progress was forced
Invariant.Assert(fEmptyOk == PTS.False);
fsfmtr.fForcedProgress = PTS.True;
}
fsfmtr.kstop = PTS.FSFMTRKSTOP.fmtrGoalReached;
}
// Set output values for floater content
pbrkrecOut = IntPtr.Zero;
fsfmtr.fContainsItemThatStoppedBeforeFootnote = PTS.False;
}
}
//-------------------------------------------------------------------
// FormatFloaterContentBottomless
//-------------------------------------------------------------------
internal override void FormatFloaterContentBottomless(
FloaterBaseParaClient paraClient, // IN:
int fSuppressTopSpace, // IN: suppress empty space at the top of the page
uint fswdir, // IN: direction of track
int fAtMaxWidth, // IN: formating is at full width of column
int durAvailable, // IN: width of available space
int dvrAvailable, // IN: height of available space
out PTS.FSFMTRBL fsfmtrbl, // OUT: result of formatting
out IntPtr pfsFloatContent, // OUT: opaque for PTS pointer pointer to formatted content
out int durFloaterWidth, // OUT: floater width
out int dvrFloaterHeight, // OUT: floater height
out PTS.FSBBOX fsbbox, // OUT: floater bbox
out int cPolygons, // OUT: number of polygons
out int cVertices) // OUT: total number of vertices in all polygons
{
Invariant.Assert(paraClient is UIElementParaClient);
Invariant.Assert(Element is BlockUIContainer);
if (fAtMaxWidth == PTS.False)
{
// BlockUIContainer is only formatted at full column width
// Set foater width, height to be greater than available values to signal to PTS that floater does not fit in the space
durFloaterWidth = durAvailable + 1;
dvrFloaterHeight = dvrAvailable + 1;
cPolygons = cVertices = 0;
fsfmtrbl = PTS.FSFMTRBL.fmtrblInterrupted;
fsbbox = new PTS.FSBBOX();
fsbbox.fDefined = PTS.False;
pfsFloatContent = IntPtr.Zero;
}
else
{
cPolygons = cVertices = 0;
// Format UIElement
if (((BlockUIContainer)Element).Child != null)
{
EnsureUIElementIsland();
FormatUIElement(durAvailable, out fsbbox);
// Set output values for floater content
pfsFloatContent = paraClient.Handle;
fsfmtrbl = PTS.FSFMTRBL.fmtrblGoalReached;
fsbbox.fDefined = PTS.True;
durFloaterWidth = fsbbox.fsrc.du;
dvrFloaterHeight = fsbbox.fsrc.dv;
}
else
{
ClearUIElementIsland();
MbpInfo mbp = MbpInfo.FromElement(Element);
fsbbox.fsrc = new PTS.FSRECT();
fsbbox.fsrc.du = durAvailable;
fsbbox.fsrc.dv = mbp.BPTop + mbp.BPBottom;
fsbbox.fDefined = PTS.True;
pfsFloatContent = paraClient.Handle;
fsfmtrbl = PTS.FSFMTRBL.fmtrblGoalReached;
durFloaterWidth = fsbbox.fsrc.du;
dvrFloaterHeight = fsbbox.fsrc.dv;
}
}
}
//-------------------------------------------------------------------
// UpdateBottomlessFloaterContent
//-------------------------------------------------------------------
internal override void UpdateBottomlessFloaterContent(
FloaterBaseParaClient paraClient, // IN:
int fSuppressTopSpace, // IN: suppress empty space at the top of the page
uint fswdir, // IN: direction of track
int fAtMaxWidth, // IN: formating is at full width of column
int durAvailable, // IN: width of available space
int dvrAvailable, // IN: height of available space
IntPtr pfsFloatContent, // IN: floater content (in UIElementParagraph, this is an alias to the paraClient)
out PTS.FSFMTRBL fsfmtrbl, // OUT: result of formatting
out int durFloaterWidth, // OUT: floater width
out int dvrFloaterHeight, // OUT: floater height
out PTS.FSBBOX fsbbox, // OUT: floater bbox
out int cPolygons, // OUT: number of polygons
out int cVertices) // OUT: total number of vertices in all polygons
{
// This implementation simply calls into format floater content bottomless. As para has no real content, this is ok.
FormatFloaterContentBottomless(paraClient, fSuppressTopSpace, fswdir, fAtMaxWidth, durAvailable, dvrAvailable, out fsfmtrbl, out pfsFloatContent,
out durFloaterWidth, out dvrFloaterHeight, out fsbbox, out cPolygons, out cVertices);
}
//-------------------------------------------------------------------
// GetMCSClientAfterFloater
//-------------------------------------------------------------------
internal override void GetMCSClientAfterFloater(
uint fswdirTrack, // IN: direction of Track
MarginCollapsingState mcs, // IN: input margin collapsing state
out IntPtr pmcsclientOut) // OUT: MCSCLIENT that floater will return to track
{
MarginCollapsingState mcsNew;
int margin;
MbpInfo mbp = MbpInfo.FromElement(Element);
MarginCollapsingState.CollapseBottomMargin(PtsContext, mbp, null, out mcsNew, out margin);
if (mcsNew != null)
{
pmcsclientOut = mcsNew.Handle;
}
else
{
pmcsclientOut = IntPtr.Zero;
}
}
#endregion PTS callbacks
//-------------------------------------------------------------------
//
// Private methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Format UIElement
/// </summary>
private void FormatUIElement(int durAvailable, out PTS.FSBBOX fsbbox)
{
MbpInfo mbp = MbpInfo.FromElement(Element);
double elementHeight;
double elementWidth = TextDpi.FromTextDpi(Math.Max(1, durAvailable - (mbp.MBPLeft + mbp.MBPRight)));
if (SizeToFigureParent)
{
// Only child of a figure whose height is set. Size to figure's page height less figure's MBP and BlockUIContainer's MBP
// NOTE: BlockUIContainer margins are always extracted before formatting, either from Figure height or page height
if (StructuralCache.CurrentFormatContext.FinitePage)
{
elementHeight = StructuralCache.CurrentFormatContext.PageHeight;
}
else
{
Figure figure = (Figure) ((BlockUIContainer)Element).Parent;
Invariant.Assert(figure.Height.IsAbsolute);
elementHeight = figure.Height.Value;
}
elementHeight = Math.Max(TextDpi.FromTextDpi(1), elementHeight - TextDpi.FromTextDpi(mbp.MBPTop + mbp.MBPBottom));
UIElementIsland.DoLayout(new Size(elementWidth, elementHeight), false, false);
// Create fsbbox. Set width to available width since we want block ui container to occupy the full column
// and UIElement to be algined within it. Set dv to elementHeight.
fsbbox.fsrc = new PTS.FSRECT();
fsbbox.fsrc.du = durAvailable;
fsbbox.fsrc.dv = TextDpi.ToTextDpi(elementHeight) + mbp.BPTop + mbp.BPBottom;
fsbbox.fDefined = PTS.True;
}
else
{
// Either BlockUIContainer is not the only child of a figure or the figure's height is unspecified.
// In this case, size to height of strcutural cache's current page less page margins and container MBP.
// This is consistent with figure's behavior on sizing to content
// Always measure at infinity for bottomless, consistent constraint.
if (StructuralCache.CurrentFormatContext.FinitePage)
{
Thickness pageMargin = StructuralCache.CurrentFormatContext.DocumentPageMargin;
elementHeight = StructuralCache.CurrentFormatContext.DocumentPageSize.Height - pageMargin.Top - pageMargin.Bottom - TextDpi.FromTextDpi(mbp.MBPTop + mbp.MBPBottom);
elementHeight = Math.Max(TextDpi.FromTextDpi(1), elementHeight);
}
else
{
elementHeight = Double.PositiveInfinity;
}
Size uiIslandSize = UIElementIsland.DoLayout(new Size(elementWidth, elementHeight), false, true);
// Create fsbbox. Set width to available width since we want block ui container to occupy the full column
// and UIElement to be algined within it
fsbbox.fsrc = new PTS.FSRECT();
fsbbox.fsrc.du = durAvailable;
fsbbox.fsrc.dv = TextDpi.ToTextDpi(uiIslandSize.Height) + mbp.BPTop + mbp.BPBottom;
fsbbox.fDefined = PTS.True;
}
}
/// <summary>
/// Create UIElementIsland representing embedded Element Layout island within content world.
/// </summary>
private void EnsureUIElementIsland()
{
if (_uiElementIsland == null)
{
_uiElementIsland = new UIElementIsland(((BlockUIContainer)Element).Child);
_uiElementIsland.DesiredSizeChanged += new DesiredSizeChangedEventHandler(OnUIElementDesiredSizeChanged);
}
}
/// <summary>
/// Clear UIElementIsland, unsubscribing from events, etc.
/// </summary>
private void ClearUIElementIsland()
{
try
{
if (_uiElementIsland != null)
{
_uiElementIsland.DesiredSizeChanged -= new DesiredSizeChangedEventHandler(OnUIElementDesiredSizeChanged);
_uiElementIsland.Dispose();
}
}
finally
{
_uiElementIsland = null;
}
}
/// <summary>
/// Handler for DesiredSizeChanged raised by UIElement island.
/// </summary>
private void OnUIElementDesiredSizeChanged(object sender, DesiredSizeChangedEventArgs e)
{
StructuralCache.FormattingOwner.OnChildDesiredSizeChanged(e.Child);
}
#endregion Private Methods
//-------------------------------------------------------------------
//
// Private Properties
//
//-------------------------------------------------------------------
#region Private Properties
/// <summary>
/// UIElementIsland representing embedded Element Layout island within content world.
/// </summary>
internal UIElementIsland UIElementIsland
{
get
{
return _uiElementIsland;
}
}
/// <summary>
/// Whether sizing to fit entire figure area.
/// </summary>
private bool SizeToFigureParent
{
get
{
// Check for auto value for figure height.
// If figure height is auto we do not size to it.
if (!IsOnlyChildOfFigure)
{
return false;
}
Figure figure = (Figure)((BlockUIContainer)Element).Parent;
if (figure.Height.IsAuto)
{
return false;
}
if (!StructuralCache.CurrentFormatContext.FinitePage && !figure.Height.IsAbsolute)
{
return false;
}
return true;
}
}
/// <summary>
/// Whether this block is the only child of figure.
/// </summary>
private bool IsOnlyChildOfFigure
{
get
{
DependencyObject parent = ((BlockUIContainer)Element).Parent;
if (parent is Figure)
{
Figure figure = parent as Figure;
if (figure.Blocks.FirstChild == figure.Blocks.LastChild &&
figure.Blocks.FirstChild == Element)
{
return true;
}
}
return false;
}
}
#endregion Private Properties
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
/// <summary>
/// UIElementIsland representing embedded ElementLayout island within content world.
/// </summary>
private UIElementIsland _uiElementIsland;
#endregion Private Fields
}
}
#pragma warning enable 1634, 1691
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
namespace MixedRealityToolkit.Common.EditorScript
{
/// <summary>
/// Helper class for launching external processes inside of the unity editor.
/// </summary>
public class ExternalProcess : IDisposable
{
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_CreateProcess([MarshalAs(UnmanagedType.LPStr)] string cmdline);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExternalProcessAPI_IsRunning(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_SendLine(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string line);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_GetLine(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_DestroyProcess(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
public static extern void ExternalProcessAPI_ConfirmOrBeginProcess([MarshalAs(UnmanagedType.LPStr)] string processName);
private IntPtr mHandle;
/// <summary>
/// First some static utility functions, used by some other code as well.
/// They are related to "external processes" so they appear here.
/// </summary>
private static string sAppDataPath;
public static void Launch(string appName)
{
// Full or relative paths only. Currently unused.
if (!appName.StartsWith(@"\"))
{
appName += @"\";
}
string appPath = AppDataPath + appName;
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.Start();
}
private static string AppDataPath
{
get
{
if (string.IsNullOrEmpty(sAppDataPath))
{
sAppDataPath = Application.dataPath.Replace("/", @"\");
}
return sAppDataPath;
}
}
public static bool FindAndLaunch(string appName)
{
return FindAndLaunch(appName, null);
}
public static bool FindAndLaunch(string appName, string args)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
string appPath = FindPathToExecutable(appName);
if (appPath == null)
{
return false;
}
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.StartInfo.Arguments = args;
return pr.Start();
}
public static string FindPathToExecutable(string appName)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
if (!appName.StartsWith(@"\"))
{
appName = @"\" + appName;
}
string searchDir = AppDataPath;
while (searchDir.Length > 3)
{
string appPath = searchDir + appName;
if (File.Exists(appPath))
{
return appPath;
}
searchDir = Path.GetDirectoryName(searchDir);
}
return null;
}
public static string MakeRelativePath(string path1, string path2)
{
// TBD- doesn't really belong in ExternalProcess.
path1 = path1.Replace('\\', '/');
path2 = path2.Replace('\\', '/');
path1 = path1.Replace("\"", "");
path2 = path2.Replace("\"", "");
Uri uri1 = new Uri(path1);
Uri uri2 = new Uri(path2);
Uri relativePath = uri1.MakeRelativeUri(uri2);
return relativePath.OriginalString;
}
/// <summary>
/// The actual ExternalProcess class.
/// </summary>
/// <param name="appName"></param>
/// <returns></returns>
public static ExternalProcess CreateExternalProcess(string appName)
{
return CreateExternalProcess(appName, null);
}
public static ExternalProcess CreateExternalProcess(string appName, string args)
{
// Seems like it would be safer and more informative to call this static method and test for null after.
try
{
return new ExternalProcess(appName, args);
}
catch (Exception ex)
{
UnityEngine.Debug.LogError("Unable to start process " + appName + ", " + ex.Message + ".");
}
return null;
}
private ExternalProcess(string appName, string args)
{
appName = appName.Replace("/", @"\");
string appPath = appName;
if (!File.Exists(appPath))
{
appPath = FindPathToExecutable(appName);
}
if (appPath == null)
{
throw new ArgumentException("Unable to find app " + appPath);
}
// This may throw, calling code should catch the exception.
string launchString = args == null ? appPath : appPath + " " + args;
mHandle = ExternalProcessAPI_CreateProcess(launchString);
}
~ExternalProcess()
{
Dispose(false);
}
public bool IsRunning()
{
try
{
if (mHandle != IntPtr.Zero)
{
return ExternalProcessAPI_IsRunning(mHandle);
}
}
catch
{
Terminate();
}
return false;
}
public bool WaitForStart(float seconds)
{
return WaitFor(seconds, () => { return ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitForShutdown(float seconds)
{
return WaitFor(seconds, () => { return !ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitFor(float seconds, Func<bool> func)
{
if (seconds <= 0.0f)
seconds = 5.0f;
float end = Time.realtimeSinceStartup + seconds;
bool hasHappened = false;
while (Time.realtimeSinceStartup < end)
{
hasHappened = func();
if (hasHappened)
{
break;
}
Thread.Sleep(Math.Min(500, (int)(seconds * 1000)));
}
return hasHappened;
}
public void SendLine(string line)
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_SendLine(mHandle, line);
}
}
catch
{
Terminate();
}
}
public string GetLine()
{
try
{
if (mHandle != IntPtr.Zero)
{
return Marshal.PtrToStringAnsi(ExternalProcessAPI_GetLine(mHandle));
}
}
catch
{
Terminate();
}
return null;
}
public void Terminate()
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_DestroyProcess(mHandle);
}
}
catch
{
// TODO: Should we be catching something here?
}
mHandle = IntPtr.Zero;
}
// IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Terminate();
}
}
}
| |
// 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 Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CertTests
{
[Fact]
public static void X509CertTest()
{
string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, [email protected]";
using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer")))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
int snlen = cert.GetSerialNumber().Length;
Assert.Equal(16, snlen);
byte[] serialNumber = new byte[snlen];
Buffer.BlockCopy(cert.GetSerialNumber(), 0,
serialNumber, 0,
snlen);
Assert.Equal(0xF6, serialNumber[0]);
Assert.Equal(0xB3, serialNumber[snlen / 2]);
Assert.Equal(0x2A, serialNumber[snlen - 1]);
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
int pklen = cert.GetPublicKey().Length;
Assert.Equal(270, pklen);
byte[] publicKey = new byte[pklen];
Buffer.BlockCopy(cert.GetPublicKey(), 0,
publicKey, 0,
pklen);
Assert.Equal(0x30, publicKey[0]);
Assert.Equal(0xB6, publicKey[9]);
Assert.Equal(1, publicKey[pklen - 1]);
}
}
[Fact]
[ActiveIssue(3893, PlatformID.AnyUnix)]
public static void X509Cert2Test()
{
string certName = @"[email protected], CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US";
DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
{
Assert.Equal(certName, cert2.IssuerName.Name);
Assert.Equal(certName, cert2.SubjectName.Name);
Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));
PublicKey pubKey = cert2.PublicKey;
Assert.Equal("RSA", pubKey.Oid.FriendlyName);
Assert.Equal(notAfter, cert2.NotAfter);
Assert.Equal(notBefore, cert2.NotBefore);
Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
Assert.Equal(3, cert2.Version);
}
}
/// <summary>
/// This test is for excerising X509Store and X509Chain code without actually installing any certificate
/// </summary>
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void X509CertStoreChain()
{
X509Store store = new X509Store("My", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
// can't guarantee there is a certificate in store
if (store.Certificates.Count > 0)
{
X509Chain chain = new X509Chain();
Assert.NotNull(chain.SafeHandle);
Assert.Same(chain.SafeHandle, chain.SafeHandle);
Assert.True(chain.SafeHandle.IsInvalid);
foreach (X509Certificate2 c in store.Certificates)
{
// can't guarantee success, so no Assert
if (chain.Build(c))
{
foreach (X509ChainElement k in chain.ChainElements)
{
Assert.NotNull(k.Certificate.IssuerName.Name);
}
}
}
}
}
[Fact]
public static void X509CertEmptyToString()
{
using (var c = new X509Certificate())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate";
Assert.Equal(expectedResult, c.ToString());
Assert.Equal(expectedResult, c.ToString(false));
Assert.Equal(expectedResult, c.ToString(true));
}
}
[Fact]
public static void X509Cert2EmptyToString()
{
using (var c2 = new X509Certificate2())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2";
Assert.Equal(expectedResult, c2.ToString());
Assert.Equal(expectedResult, c2.ToString(false));
Assert.Equal(expectedResult, c2.ToString(true));
}
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void X509Cert2ToStringVerbose()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 c in store.Certificates)
{
Assert.False(string.IsNullOrWhiteSpace(c.ToString(true)));
c.Dispose();
}
}
}
[Fact]
public static void X509Cert2CreateFromEmptyPfx()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx));
}
[Fact]
public static void X509Cert2CreateFromPfxFile()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx")))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Cert2CreateFromPfxWithPassword()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test"))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
[ActiveIssue(2635)]
public static void X509Certificate2FromPkcs7DerFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b")));
}
[Fact]
[ActiveIssue(2635)]
public static void X509Certificate2FromPkcs7PemFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c")));
}
[Fact]
public static void X509Certificate2FromPkcs7DerBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes));
}
[Fact]
public static void X509Certificate2FromPkcs7PemBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes));
}
[Fact]
public static void UseAfterDispose()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
// Do a couple of things that would only be true on a valid certificate, as a precondition.
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
c.Dispose();
// For compat reasons, Dispose() acts like the now-defunct Reset() method rather than
// causing ObjectDisposedExceptions.
h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => c.Subject);
}
}
[Fact]
public static void ExportPublicKeyAsPkcs12()
{
using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate))
{
// Pre-condition: There's no private key
Assert.False(publicOnly.HasPrivateKey);
// This won't throw.
byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12);
// Read it back as a collection, there should be only one cert, and it should
// be equal to the one we started with.
X509Certificate2Collection fromPfx = new X509Certificate2Collection();
fromPfx.Import(pkcs12Bytes);
Assert.Equal(1, fromPfx.Count);
Assert.Equal(publicOnly, fromPfx[0]);
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kodestruct.Common.Mathematics;
using Kodestruct.Common.Section.Interfaces;
namespace Kodestruct.Common.Section.SectionTypes
{
public class SectionThinWall : CompoundShape
{
private List<ThinWallSegment> segments;
private List<ThinWallSegment> SegmentsCentered;
public List<ThinWallSegment> Segments
{
get { return segments; }
set { segments = value; }
}
public SectionThinWall(List<ThinWallSegment> Segments): base(null)
{
this.Segments = StraightenSegments(Segments);
AdjustCoordinates();
}
private List<ThinWallSegment> StraightenSegments(List<ThinWallSegment> OriginalSegments)
{
// straighten sements that are slightly off axis
List<ThinWallSegment> segs = OriginalSegments.Select(s =>
{
Line2D lin;
if (Math.Abs((s.Line.StartPoint.X - s.Line.EndPoint.X) / (s.Line.StartPoint.Y - s.Line.EndPoint.Y))<0.01)
{
lin = new Line2D(new Point2D(s.Line.StartPoint.X, s.Line.StartPoint.Y), new Point2D(s.Line.StartPoint.X, s.Line.EndPoint.Y));
}
else if (Math.Abs((s.Line.StartPoint.Y - s.Line.EndPoint.Y) / (s.Line.StartPoint.X - s.Line.EndPoint.X))<0.01)
{
lin = new Line2D(new Point2D(s.Line.StartPoint.X, s.Line.StartPoint.Y), new Point2D(s.Line.EndPoint.X, s.Line.StartPoint.Y));
}
else
{
lin = new Line2D(new Point2D(s.Line.StartPoint.X, s.Line.StartPoint.Y), new Point2D(s.Line.EndPoint.X, s.Line.EndPoint.Y));
}
return new ThinWallSegment(lin, s.WallThickness);
}).ToList();
return segs;
}
private void AdjustCoordinates()
{
//move all rectangles to respect centroid
Point2D centr = this.CalculateLineCentroidCoordinate();
SegmentsCentered = this.Segments.Select(s =>
new ThinWallSegment(new Line2D(
new Point2D(s.Line.StartPoint.X-centr.X,s.Line.StartPoint.Y-centr.Y),
new Point2D(s.Line.EndPoint.X-centr.X,s.Line.EndPoint.Y-centr.Y)),
s.WallThickness)
).ToList();
}
private Point2D CalculateLineCentroidCoordinate()
{
double Xcen = this.Segments.Sum(s =>
s.Line.Length * s.WallThickness*(s.Line.EndPoint.X + s.Line.StartPoint.X)/2.0);
double cenArea = this.Segments.Sum(s =>
s.Line.Length * s.WallThickness
);
double cenX = Xcen/cenArea;
double Ycen = this.Segments.Sum(s =>
s.Line.Length * s.WallThickness*(s.Line.EndPoint.Y + s.Line.StartPoint.Y)/2.0);
double cenY = Ycen / cenArea;
return new Point2D(cenX, cenY);
}
public override List<CompoundShapePart> GetCompoundRectangleXAxisList()
{
List<ThinWallSegment> YSegments = new List<ThinWallSegment>();
List<double> YUnique = GetUniqueYCoordinates(SegmentsCentered);
List<ThinWallSegment> crossingSegments = GetSubdividedYSegments(YUnique, SegmentsCentered);
List<CompoundShapePart> ProjectedRectangles = GetProjectedYRectangles(crossingSegments);
List<CompoundShapePart> ConsolidatedRectangles = GetConsolidatedRectangles(ProjectedRectangles);
return ConsolidatedRectangles;
}
public override List<CompoundShapePart> GetCompoundRectangleYAxisList()
{
List<ThinWallSegment> XSegments = GetRotatedSegments(SegmentsCentered);
List<double> YUnique = GetUniqueYCoordinates(XSegments);
List<ThinWallSegment> crossingSegments = GetSubdividedYSegments(YUnique, XSegments);
List<CompoundShapePart> ProjectedRectangles = GetProjectedYRectangles(crossingSegments);
List<CompoundShapePart> ConsolidatedRectangles = GetConsolidatedRectangles(ProjectedRectangles);
return ConsolidatedRectangles;
}
private List<ThinWallSegment> GetRotatedSegments(List<ThinWallSegment> segments)
{
//Flip X and Y coordinates
List<ThinWallSegment> newSegs = segments.Select(s =>
{
ThinWallSegment sg = new ThinWallSegment(new Line2D(new Point2D(s.Line.StartPoint.Y, s.Line.StartPoint.X), new Point2D(s.Line.EndPoint.Y, s.Line.EndPoint.X)), s.WallThickness);
return sg;
}).ToList();
return newSegs;
}
#region Y coordinates
private List<CompoundShapePart> GetConsolidatedRectangles(List<CompoundShapePart> ProjectedRectangles)
{
List<CompoundShapePart> consolidatedRectangles = new List<CompoundShapePart>();
List<double> YUnique = GetUniqueYCoordinates(ProjectedRectangles);
double YCentroid = 0;
for (int i = 0; i < YUnique.Count() - 1; i++)
{
double height = YUnique[i + 1] - YUnique[i];
YCentroid = (YUnique[i + 1] + YUnique[i]) / 2.0;
var combinedWidth = ProjectedRectangles.Where(r =>
r.Ymin <= YUnique[i] && r.Ymax >= YUnique[i + 1]
).Sum(r => r.b);
consolidatedRectangles.Add(new CompoundShapePart(combinedWidth, height, new Point2D(0, YCentroid)));
}
return consolidatedRectangles;
}
private List<CompoundShapePart> GetProjectedYRectangles(List<ThinWallSegment> crossingSegments)
{
List<CompoundShapePart> ProjectedSegments = new List<CompoundShapePart>();
foreach (var s in crossingSegments)
{
CompoundShapePart p;
double dy = s.Line.YMax - s.Line.YMin;
double dx = s.Line.XMax - s.Line.XMin;
double L = s.Line.Length;
if (dy / dx < 0.05)
{
//HORIZONTAL LINE
p = new CompoundShapePart(dx, s.WallThickness, new Point2D(0,s.Line.YMax));
}
else
{
//VERTICAL LINE
if (dx / dy < 0.05)
{
p = new CompoundShapePart(s.WallThickness, dy, new Point2D(0, (s.Line.YMax + s.Line.YMin)/2.0));
}
else
{
//SLOPED LINE
double angleFromHorizontal = Math.Atan(dy / dx);
double t_eff = s.WallThickness / Math.Sin(angleFromHorizontal);
p = new CompoundShapePart(t_eff, dy, new Point2D(0, (s.Line.YMax + s.Line.YMin) / 2.0));
}
}
ProjectedSegments.Add(p);
}
return ProjectedSegments.OrderBy(r => r.InsertionPoint.Y).ToList();
}
private List<ThinWallSegment> GetSubdividedYSegments(List<double> YUnique, List<ThinWallSegment> Segs)
{
List<ThinWallSegment> segments = new List<ThinWallSegment>();
for (int i = 0; i < YUnique.Count(); i++)
{
//double DeltaY = YUnique[i + 1] - YUnique[i];
List<ThinWallSegment> crossingVericalSegments = Segs.Where(s =>
{
//if this is a level line
if (s.Line.YMax != s.Line.YMin)
{
if (i != 0)
{
if (s.Line.YMin < YUnique[i] && s.Line.YMax >= YUnique[i])
{
return true;
}
else
{
return false;
}
}
//if this is the lowest coordinate
else
{
return false;
}
//s.Line.YMin <= YUnique[i] & s.Line.YMin >= YUnique[i + 1]
}
else
{
return false;
}
}
).ToList();
if (crossingVericalSegments.Count() == 0)
{
//if this segment is a gap
if (i != 0)
{
segments.Add(new ThinWallSegment(YUnique[i-1], YUnique[i], 0));
}
}
else
{
//if this segment is NOT a gap
foreach (var s in crossingVericalSegments)
{
if (i != 0)
{
Line2D subLine = s.Line.GetSubSegment(YUnique[i-1], YUnique[i]);
ThinWallSegment seg = new ThinWallSegment(subLine, s.WallThickness);
segments.Add(seg);
}
else
{
ThinWallSegment seg = new ThinWallSegment(s.Line, s.WallThickness);
segments.Add(seg);
}
}
}
List<ThinWallSegment> crossingHorizontalSegments = Segs.Where(s =>
{
//if this is a level line
if (s.Line.YMax == s.Line.YMin)
{
if (s.Line.YMin == YUnique[i])
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}).ToList();
segments.AddRange(crossingHorizontalSegments);
}
return segments.OrderBy(c => c.Line.StartPoint.Y).ToList();
}
private List<double> GetUniqueYCoordinates(List<ThinWallSegment> Segments)
{
List<double> uniqueCoordinates = Segments.Select(s => s.Line.YMin).ToList();
uniqueCoordinates.AddRange(Segments.Select(s => s.Line.YMax).ToList());
return uniqueCoordinates.Distinct().ToList().OrderBy(d => d).ToList();
}
private List<double> GetUniqueYCoordinates(List<CompoundShapePart> ProjectedRectangles)
{
List<double> uniqueCoordinates = ProjectedRectangles.Select(s => s.Ymin).ToList();
uniqueCoordinates.AddRange(ProjectedRectangles.Select(s => s.Ymax).ToList());
return uniqueCoordinates.Distinct().ToList().OrderBy(d => d).ToList();
}
#endregion
#region X coordinates
//private List<CompoundShapePart> GetProjectedXRectangles(List<ThinWallSegment> crossingSegments)
//{
// List<CompoundShapePart> ProjectedSegments = new List<CompoundShapePart>();
// foreach (var s in crossingSegments)
// {
// CompoundShapePart p;
// double dy = s.Line.XMax - s.Line.XMin;
// double dx = s.Line.XMax - s.Line.XMin;
// double L = s.Line.Length;
// if (dy / dx < 0.05)
// {
// p = new CompoundShapePart( s.WallThickness, dx, new Point2D(0, s.Line.XMin - s.WallThickness / 2.0));
// }
// else
// {
// if (dx / dy < 0.05)
// {
// p = new CompoundShapePart(dy, s.WallThickness, new Point2D(0, s.Line.XMin));
// }
// else
// {
// //Skewed segment
// double angleFromHorizontal = Math.Atan(dy / dx);
// p = new CompoundShapePart(dx / Math.Cos(angleFromHorizontal), dy, new Point2D(0, s.Line.XMin));
// }
// }
// ProjectedSegments.Add(p);
// }
// return ProjectedSegments;
//}
//private List<ThinWallSegment> GetSubdividedXSegments(List<double> XUnique)
//{
// List<ThinWallSegment> segments = new List<ThinWallSegment>();
// for (int i = 0; i < XUnique.Count() - 1; i++)
// {
// double DeltaX = XUnique[i + 1] - XUnique[i];
// var crossingSegments = Segments.Where(s =>
// s.Line.XMin <= XUnique[i] & s.Line.XMin >= XUnique[i + 1]).ToList();
// if (crossingSegments.Count() == 0)
// {
// //if this segment is a gap
// segments.Add(new ThinWallSegment(XUnique[i], XUnique[i + 1], 0));
// }
// else
// {
// //if this segment is NOT a gap
// foreach (var s in Segments)
// {
// if (s.Line.XMin <= XUnique[i] && s.Line.XMax >= XUnique[i + 1])
// {
// Line2D subLine = s.Line.GetSubSegment(XUnique[i], XUnique[i + 1]);
// ThinWallSegment seg = new ThinWallSegment(subLine, s.WallThickness);
// segments.Add(seg);
// }
// }
// }
// }
// return segments;
//}
//private List<double> GetUniqueXCoordinates(List<ThinWallSegment> Segments)
//{
// List<double> uniqueCoordinates = Segments.Select(s => s.Line.XMin).ToList();
// uniqueCoordinates.AddRange(Segments.Select(s => s.Line.XMax).ToList());
// return uniqueCoordinates.Distinct().ToList().OrderBy(d => d).ToList();
//}
#endregion
protected override void CalculateWarpingConstant()
{
_C_w = 0;
}
}
}
| |
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel
//
// 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.Xml.Serialization;
namespace SharpDocPak
{
/// <summary>
/// Tag index.
/// </summary>
[Serializable]
public class TagIndex : IEquatable<TagIndex>
{
public const string TitleId = "title";
public const string ContentId = "content";
/// <summary>
/// Gets the default index of the title.
/// </summary>
/// <value>The default index of the title.</value>
public static TagIndex DefaultTitleIndex
{
get
{
return new TagIndex(TitleId, "//html/head/title", "Title");
}
}
/// <summary>
/// Gets the default index of the content.
/// </summary>
/// <value>The default index of the content.</value>
public static TagIndex DefaultContentIndex
{
get
{
return new TagIndex(ContentId, "//html/body", "Content");
}
}
/// <summary>
/// Gets the default tags.
/// </summary>
/// <value>The default tags.</value>
public static List<TagIndex> DefaultTags
{
get { return new List<TagIndex> {DefaultTitleIndex, DefaultContentIndex}; }
}
/// <summary>
/// Adds the tag index to the tag list.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="tagIndex">Index of the tag.</param>
public static void AddTagIndex(List<TagIndex> tags, TagIndex tagIndex)
{
tags.Remove(tagIndex);
tags.Add(tagIndex);
}
/// <summary>
/// Parses the tag index and add it to tag list.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="tagId">The tag id.</param>
/// <param name="xpathAndName">The xpath with an optional name separated by a semi-colon ';'.</param>
public static void ParseAndAddTagIndex(List<TagIndex> tags, string tagId, string xpathAndName)
{
var tagIndex = new TagIndex() {Id = tagId};
var separatorIndex = xpathAndName.IndexOf(';');
if (separatorIndex > 0)
{
tagIndex.TagPath = xpathAndName.Substring(0, separatorIndex);
tagIndex.Name = xpathAndName.Substring(separatorIndex + 1, xpathAndName.Length - separatorIndex - 1);
} else
{
tagIndex.TagPath = xpathAndName;
tagIndex.Name = "" + char.ToUpper(tagId[0]) + tagId.Substring(1);
}
AddTagIndex(tags, tagIndex);
}
/// <summary>
/// Initializes a new instance of the <see cref="TagIndex"/> class.
/// </summary>
public TagIndex()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TagIndex"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="tagPath">The tag xpath.</param>
/// <param name="name">The name.</param>
public TagIndex(string id, string tagPath, string name)
{
Id = id;
TagPath = tagPath;
Name = name;
}
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[XmlAttribute("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the tag xpath.
/// </summary>
/// <value>The tag xpath.</value>
[XmlAttribute("xpath")]
public string TagPath { get; set; }
/// <summary>
/// Gets or sets the display name.
/// </summary>
/// <value>The display name.</value>
[XmlAttribute("name")]
public string Name { get; set; }
/// <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>
public bool Equals(TagIndex other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Id, Id);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (TagIndex)) return false;
return Equals((TagIndex) obj);
}
/// <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>
public override int GetHashCode()
{
return (Id != null ? Id.GetHashCode() : 0);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(TagIndex left, TagIndex right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(TagIndex left, TagIndex right)
{
return !Equals(left, right);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sep.Git.Tfs.Commands;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.Core
{
public class TfsWorkspace : ITfsWorkspace
{
private readonly IWorkspace _workspace;
private readonly string _localDirectory;
private readonly TextWriter _stdout;
private readonly TfsChangesetInfo _contextVersion;
private readonly CheckinOptions _checkinOptions;
private readonly ITfsHelper _tfsHelper;
private readonly CheckinPolicyEvaluator _policyEvaluator;
public IGitTfsRemote Remote { get; private set; }
public TfsWorkspace(IWorkspace workspace, string localDirectory, TextWriter stdout, TfsChangesetInfo contextVersion, IGitTfsRemote remote, CheckinOptions checkinOptions, ITfsHelper tfsHelper, CheckinPolicyEvaluator policyEvaluator)
{
_workspace = workspace;
_policyEvaluator = policyEvaluator;
_contextVersion = contextVersion;
_checkinOptions = checkinOptions;
_tfsHelper = tfsHelper;
_localDirectory = localDirectory;
_stdout = stdout;
this.Remote = remote;
}
public void Shelve(string shelvesetName, bool evaluateCheckinPolicies, Func<string> generateCheckinComment)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to shelve!");
var shelveset = _tfsHelper.CreateShelveset(_workspace, shelvesetName);
shelveset.Comment = string.IsNullOrWhiteSpace(_checkinOptions.CheckinComment) && !_checkinOptions.NoGenerateCheckinComment ? generateCheckinComment() : _checkinOptions.CheckinComment;
shelveset.WorkItemInfo = GetWorkItemInfos().ToArray();
if (evaluateCheckinPolicies)
{
foreach (var message in _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, shelveset.Comment, null, shelveset.WorkItemInfo).Messages)
{
_stdout.WriteLine("[Checkin Policy] " + message);
}
}
_workspace.Shelve(shelveset, pendingChanges, _checkinOptions.Force ? TfsShelvingOptions.Replace : TfsShelvingOptions.None);
}
public long CheckinTool(Func<string> generateCheckinComment)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var checkinComment = _checkinOptions.CheckinComment;
if (string.IsNullOrWhiteSpace(checkinComment) && !_checkinOptions.NoGenerateCheckinComment)
checkinComment = generateCheckinComment();
var newChangesetId = _tfsHelper.ShowCheckinDialog(_workspace, pendingChanges, GetWorkItemCheckedInfos(), checkinComment);
if (newChangesetId <= 0)
throw new GitTfsException("Checkin cancelled!");
return newChangesetId;
}
public void Merge(string sourceTfsPath, string tfsRepositoryPath)
{
_workspace.Merge(sourceTfsPath, tfsRepositoryPath);
}
public long Checkin(CheckinOptions options)
{
if (options == null) options = _checkinOptions;
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var workItemInfos = GetWorkItemInfos(options);
var checkinNote = _tfsHelper.CreateCheckinNote(options.CheckinNotes);
var checkinProblems = _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, options.CheckinComment, checkinNote, workItemInfos);
if (checkinProblems.HasErrors)
{
foreach (var message in checkinProblems.Messages)
{
if (options.Force && string.IsNullOrWhiteSpace(options.OverrideReason) == false)
{
_stdout.WriteLine("[OVERRIDDEN] " + message);
}
else
{
_stdout.WriteLine("[ERROR] " + message);
}
}
if (!options.Force)
{
throw new GitTfsException("No changes checked in.");
}
if (String.IsNullOrWhiteSpace(options.OverrideReason))
{
throw new GitTfsException("A reason must be supplied (-f REASON) to override the policy violations.");
}
}
var policyOverride = GetPolicyOverrides(options, checkinProblems.Result);
var newChangeset = _workspace.Checkin(pendingChanges, options.CheckinComment, options.AuthorTfsUserId, checkinNote, workItemInfos, policyOverride, options.OverrideGatedCheckIn);
if (newChangeset == 0)
{
throw new GitTfsException("Checkin failed!");
}
else
{
return newChangeset;
}
}
private TfsPolicyOverrideInfo GetPolicyOverrides(CheckinOptions options, ICheckinEvaluationResult checkinProblems)
{
if (!options.Force || String.IsNullOrWhiteSpace(options.OverrideReason))
return null;
return new TfsPolicyOverrideInfo { Comment = options.OverrideReason, Failures = checkinProblems.PolicyFailures };
}
public string GetLocalPath(string path)
{
return Path.Combine(_localDirectory, path);
}
public void Add(string path)
{
_stdout.WriteLine(" add " + path);
var added = _workspace.PendAdd(GetLocalPath(path));
if (added != 1) throw new Exception("One item should have been added, but actually added " + added + " items.");
}
public void Edit(string path)
{
path = GetLocalPath(path);
_stdout.WriteLine(" edit " + path);
GetFromTfs(path);
var edited = _workspace.PendEdit(path);
if (edited != 1) throw new Exception("One item should have been edited, but actually edited " + edited + " items.");
}
public void Delete(string path)
{
path = GetLocalPath(path);
_stdout.WriteLine(" delete " + path);
GetFromTfs(path);
var deleted = _workspace.PendDelete(path);
if (deleted != 1) throw new Exception("One item should have been deleted, but actually deleted " + deleted + " items.");
}
public void Rename(string pathFrom, string pathTo, string score)
{
_stdout.WriteLine(" rename " + pathFrom + " to " + pathTo + " (score: " + score + ")");
GetFromTfs(GetLocalPath(pathFrom));
var result = _workspace.PendRename(GetLocalPath(pathFrom), GetLocalPath(pathTo));
if (result != 1) throw new ApplicationException("Unable to rename item from " + pathFrom + " to " + pathTo);
}
private void GetFromTfs(string path)
{
_workspace.ForceGetFile(_workspace.GetServerItemForLocalItem(path), (int)_contextVersion.ChangesetId);
}
public void Get(int changesetId)
{
_workspace.GetSpecificVersion(changesetId);
}
public void Get(IChangeset changeset)
{
changeset.Get(_workspace);
}
private IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(CheckinOptions options = null)
{
return GetWorkItemInfosHelper<IWorkItemCheckinInfo>(_tfsHelper.GetWorkItemInfos, options);
}
private IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos()
{
return GetWorkItemInfosHelper<IWorkItemCheckedInfo>(_tfsHelper.GetWorkItemCheckedInfos);
}
private IEnumerable<T> GetWorkItemInfosHelper<T>(Func<IEnumerable<string>, TfsWorkItemCheckinAction, IEnumerable<T>> func, CheckinOptions options = null)
{
var checkinOptions = options ?? _checkinOptions;
var workItemInfos = func(checkinOptions.WorkItemsToAssociate, TfsWorkItemCheckinAction.Associate);
workItemInfos = workItemInfos.Append(
func(checkinOptions.WorkItemsToResolve, TfsWorkItemCheckinAction.Resolve));
return workItemInfos;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestList2Tests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
var props = Properties<string, string>.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
[Test]
public void InterestList2()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterAllKeys,
new string[] { RegionNames[0], RegionNames[1] });
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
m_client2.Call(RegisterAllKeys, new string[] { RegionNames[0] });
Util.Log("StepFour complete.");
m_client1.Call(StepFiveIL);
m_client1.Call(UnregisterAllKeys, new string[] { RegionNames[1] });
Util.Log("StepFive complete.");
m_client2.Call(StepSixIL);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenIL);
Util.Log("StepSeven complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.