context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Xunit;
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public class MappedDiagnosticsContextTests
{
/// <summary>
/// Same as <see cref="MappedDiagnosticsContext" />, but there is one <see cref="MappedDiagnosticsContext"/> per each thread.
/// </summary>
[Fact]
public void MDCTest1()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
MappedDiagnosticsContext.Clear();
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.False(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2"));
Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count);
MappedDiagnosticsContext.Set("foo", "bar");
MappedDiagnosticsContext.Set("foo2", "bar2");
Assert.True(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal("bar", MappedDiagnosticsContext.Get("foo"));
Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count);
MappedDiagnosticsContext.Remove("foo");
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.True(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2"));
Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count);
Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2"));
Assert.Null(MappedDiagnosticsContext.GetObject("foo3"));
MappedDiagnosticsContext.Set("foo3", new { One = 1 });
}
catch (Exception exception)
{
lock (exceptions)
{
exceptions.Add(exception);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
[Fact]
public void MDCTest2()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
MappedDiagnosticsContext.Clear();
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.False(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2"));
MappedDiagnosticsContext.Set("foo", "bar");
MappedDiagnosticsContext.Set("foo2", "bar2");
Assert.True(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal("bar", MappedDiagnosticsContext.Get("foo"));
MappedDiagnosticsContext.Remove("foo");
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.True(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2"));
Assert.Null(MappedDiagnosticsContext.GetObject("foo3"));
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
[Fact]
public void timer_cannot_inherit_mappedcontext()
{
object getObject = null;
string getValue = null;
var mre = new ManualResetEvent(false);
Timer thread = new Timer((s) =>
{
try
{
getObject = MappedDiagnosticsContext.GetObject("DoNotExist");
getValue = MappedDiagnosticsContext.Get("DoNotExistEither");
}
finally
{
mre.Set();
}
});
thread.Change(0, Timeout.Infinite);
mre.WaitOne();
Assert.Null(getObject);
Assert.Empty(getValue);
}
[Fact]
public void disposable_removes_item()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string itemRemovedKey = "itemRemovedKey";
MappedDiagnosticsContext.Clear();
MappedDiagnosticsContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsContext.SetScoped(itemRemovedKey, "itemRemoved"))
{
Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey });
}
Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void dispose_is_idempotent()
{
const string itemKey = "itemKey";
MappedDiagnosticsContext.Clear();
IDisposable disposable = MappedDiagnosticsContext.SetScoped(itemKey, "item1");
disposable.Dispose();
Assert.False(MappedDiagnosticsContext.Contains(itemKey));
//This item shouldn't be removed since it is not the disposable one
MappedDiagnosticsContext.Set(itemKey, "item2");
disposable.Dispose();
Assert.True(MappedDiagnosticsContext.Contains(itemKey));
}
}
}
| |
//
// System.Web.StaticFileHandler
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
//
// (C) 2002 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using NServiceKit.Common;
using NServiceKit.Common.Web;
using NServiceKit.Logging;
using NServiceKit.ServiceHost;
using NServiceKit.Text;
using NServiceKit.WebHost.Endpoints.Extensions;
using HttpRequestWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpRequestWrapper;
using HttpResponseWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpResponseWrapper;
namespace NServiceKit.WebHost.Endpoints.Support
{
/// <summary>A static file handler.</summary>
public class StaticFileHandler : IHttpHandler, INServiceKitHttpHandler
{
private static readonly ILog log = LogManager.GetLogger(typeof(StaticFileHandler));
/// <summary>Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.</summary>
///
/// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to
/// service HTTP requests.
/// </param>
public void ProcessRequest(HttpContext context)
{
ProcessRequest(
new HttpRequestWrapper(null, context.Request),
new HttpResponseWrapper(context.Response),
null);
}
private DateTime DefaultFileModified { get; set; }
private string DefaultFilePath { get; set; }
private byte[] DefaultFileContents { get; set; }
/// <summary>
/// Keep default file contents in-memory
/// </summary>
/// <param name="defaultFilePath"></param>
public void SetDefaultFile(string defaultFilePath)
{
try
{
this.DefaultFileContents = File.ReadAllBytes(defaultFilePath);
this.DefaultFilePath = defaultFilePath;
this.DefaultFileModified = File.GetLastWriteTime(defaultFilePath);
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
}
/// <summary>Process the request.</summary>
///
/// <exception cref="HttpException"> Thrown when a HTTP error condition occurs.</exception>
/// <exception cref="HttpListenerException">Thrown when a HTTP Listener error condition occurs.</exception>
///
/// <param name="request"> The HTTP request.</param>
/// <param name="response"> The HTTP resource.</param>
/// <param name="operationName">Name of the operation.</param>
public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
{
response.EndHttpHandlerRequest(skipClose: true, afterBody: r => {
var fileName = request.GetPhysicalPath();
var fi = new FileInfo(fileName);
if (!fi.Exists)
{
if ((fi.Attributes & FileAttributes.Directory) != 0)
{
foreach (var defaultDoc in EndpointHost.Config.DefaultDocuments)
{
var defaultFileName = Path.Combine(fi.FullName, defaultDoc);
if (!File.Exists(defaultFileName)) continue;
r.Redirect(request.GetPathUrl() + '/' + defaultDoc);
return;
}
}
if (!fi.Exists)
{
var originalFileName = fileName;
if (Env.IsMono)
{
//Create a case-insensitive file index of all host files
if (allFiles == null)
allFiles = CreateFileIndex(request.ApplicationFilePath);
if (allDirs == null)
allDirs = CreateDirIndex(request.ApplicationFilePath);
if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
{
fi = new FileInfo(fileName);
}
}
if (!fi.Exists)
{
var msg = "Static File '" + request.PathInfo + "' not found.";
log.WarnFormat("{0} in path: {1}", msg, originalFileName);
throw new HttpException(404, msg);
}
}
}
TimeSpan maxAge;
if (r.ContentType != null && EndpointHost.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
{
r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
}
if (request.HasNotModifiedSince(fi.LastWriteTime))
{
r.ContentType = MimeTypes.GetMimeType(fileName);
r.StatusCode = 304;
return;
}
try
{
r.AddHeaderLastModified(fi.LastWriteTime);
r.ContentType = MimeTypes.GetMimeType(fileName);
if (fileName.EqualsIgnoreCase(this.DefaultFilePath))
{
if (fi.LastWriteTime > this.DefaultFileModified)
SetDefaultFile(this.DefaultFilePath); //reload
r.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length);
r.Close();
return;
}
if (EndpointHost.Config.AllowPartialResponses)
r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
long contentLength = fi.Length;
long rangeStart, rangeEnd;
var rangeHeader = request.Headers[HttpHeaders.Range];
if (EndpointHost.Config.AllowPartialResponses && rangeHeader != null)
{
rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);
if (rangeEnd > contentLength - 1)
rangeEnd = contentLength - 1;
r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
}
else
{
rangeStart = 0;
rangeEnd = contentLength - 1;
r.SetContentLength(contentLength); //throws with ASP.NET webdev server non-IIS pipelined mode
}
var outputStream = r.OutputStream;
using (var fs = fi.OpenRead())
{
if (rangeStart != 0 || rangeEnd != fi.Length - 1)
{
fs.WritePartialTo(outputStream, rangeStart, rangeEnd);
}
else
{
fs.WriteTo(outputStream);
outputStream.Flush();
}
}
}
catch (System.Net.HttpListenerException ex)
{
if (ex.ErrorCode == 1229)
return;
//Error: 1229 is "An operation was attempted on a nonexistent network connection"
//This exception occures when http stream is terminated by web browser because user
//seek video forward and new http request will be sent by browser
//with attribute in header "Range: bytes=newSeekPosition-"
throw;
}
catch (Exception ex)
{
log.ErrorFormat("Static file {0} forbidden: {1}", request.PathInfo, ex.Message);
throw new HttpException(403, "Forbidden.");
}
});
}
static Dictionary<string, string> CreateFileIndex(string appFilePath)
{
log.Debug("Building case-insensitive fileIndex for Mono at: "
+ appFilePath);
var caseInsensitiveLookup = new Dictionary<string, string>();
foreach (var file in GetFiles(appFilePath))
{
caseInsensitiveLookup[file.ToLower()] = file;
}
return caseInsensitiveLookup;
}
static Dictionary<string, string> CreateDirIndex(string appFilePath)
{
var indexDirs = new Dictionary<string, string>();
foreach (var dir in GetDirs(appFilePath))
{
indexDirs[dir.ToLower()] = dir;
}
return indexDirs;
}
/// <summary>Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.</summary>
///
/// <value>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</value>
public bool IsReusable
{
get { return true; }
}
/// <summary>Queries if a given directory exists.</summary>
///
/// <param name="dirPath"> Pathname of the directory.</param>
/// <param name="appFilePath">Full pathname of the application file.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool DirectoryExists(string dirPath, string appFilePath)
{
if (dirPath == null) return false;
try
{
if (!Env.IsMono)
return Directory.Exists(dirPath);
}
catch
{
return false;
}
if (allDirs == null)
allDirs = CreateDirIndex(appFilePath);
var foundDir = allDirs.ContainsKey(dirPath.ToLower());
//log.DebugFormat("Found dirPath {0} in Mono: ", dirPath, foundDir);
return foundDir;
}
private static Dictionary<string, string> allDirs; //populated by GetFiles()
private static Dictionary<string, string> allFiles;
static IEnumerable<string> GetFiles(string path)
{
var queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0)
{
path = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(path))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i];
}
}
}
}
static List<string> GetDirs(string path)
{
var queue = new Queue<string>();
queue.Enqueue(path);
var results = new List<string>();
while (queue.Count > 0)
{
path = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(path))
{
queue.Enqueue(subDir);
results.Add(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
return results;
}
}
}
| |
//
// Paths.cs
//
// Author:
// Aaron Bockover <[email protected]>
// Ruben Vermeersch <[email protected]>
//
// Copyright (C) 2005-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.IO;
using System;
using System.Text;
namespace Hyena
{
public static class Paths
{
public const char UnixSeparator = ':';
public const char DosSeparator = ';';
public static class Folder
{
public const char UnixSeparator = '/';
public const char DosSeparator = '\\';
}
public static string GetTempFileName (string dir)
{
return GetTempFileName (dir, null);
}
public static string GetTempFileName (string dir, string extension)
{
return GetTempFileName (new DirectoryInfo (dir), extension);
}
public static string GetTempFileName (DirectoryInfo dir, string extension)
{
string path = null;
if (dir == null || !dir.Exists) {
throw new DirectoryNotFoundException ();
}
do {
string guid = Guid.NewGuid ().ToString ();
string file = extension == null ? guid : String.Format ("{0}.{1}", guid, extension);
path = Path.Combine (dir.FullName, file);
} while (File.Exists (path));
return path;
}
public static string Combine (string first, params string [] components)
{
if (String.IsNullOrEmpty (first)) {
throw new ArgumentException ("First component must not be null or empty", "first");
} else if (components == null || components.Length < 1) {
throw new ArgumentException ("One or more path components must be provided", "components");
}
string result = first;
foreach (string component in components) {
result = Path.Combine (result, component);
}
return result;
}
public static string FindProgramInPath (string command)
{
foreach (string path in GetExecPaths ()) {
string full_path = Path.Combine (path, command);
try {
FileInfo info = new FileInfo (full_path);
// FIXME: System.IO is super lame, should check for 0755
if (info.Exists) {
return full_path;
}
} catch {
}
}
return null;
}
private static string [] GetExecPaths ()
{
string path = Environment.GetEnvironmentVariable ("PATH");
if (String.IsNullOrEmpty (path)) {
return new string [] { "/bin", "/usr/bin", "/usr/local/bin" };
}
// this is super lame, should handle quoting/escaping
return path.Split (UnixSeparator);
}
public static string SwitchRoot (string path, string mountPoint, string rootPath)
{
if (!path.StartsWith (mountPoint)) {
throw new ArgumentException ("mountPoint must be contained in first part of the path");
}
return path.Replace (mountPoint, rootPath);
}
public static string MakePathRelative (string path, string to)
{
if (String.IsNullOrEmpty (path) || String.IsNullOrEmpty (to)) {
return null;
}
if (Path.IsPathRooted (path) ^ Path.IsPathRooted (to))
{
// one path is absolute, one path is relative, impossible to compare
return null;
}
if (path == to) {
return String.Empty;
}
if (to[to.Length - 1] != Path.DirectorySeparatorChar) {
to = to + Path.DirectorySeparatorChar;
}
if (path.StartsWith (to))
{
return path.Substring (to.Length);
}
return BuildRelativePath (path, to);
}
private static string BuildRelativePath (string path, string to)
{
var toParts = to.Split (Path.DirectorySeparatorChar);
var pathParts = path.Split (Path.DirectorySeparatorChar);
var i = 0;
while (i < toParts.Length && i < pathParts.Length && toParts [i] == pathParts [i]) {
i++;
}
var relativePath = new StringBuilder ();
for (int j = 0; j < toParts.Length - i - 1; j++) {
relativePath.Append ("..");
relativePath.Append (Path.DirectorySeparatorChar);
}
var required = new string [pathParts.Length - i];
for (int j = i; j < pathParts.Length; j++) {
required [j - i] = pathParts [j];
}
relativePath.Append (String.Join (Path.DirectorySeparatorChar.ToString (), required));
return relativePath.ToString ();
}
public static string NormalizeToDos (string path)
{
return path.Replace (Folder.UnixSeparator, Folder.DosSeparator);
}
public static string NormalizeToUnix (string path)
{
if (!path.Contains (Folder.UnixSeparator.ToString ()) && path.Contains (Folder.DosSeparator.ToString ())) {
return path.Replace (Folder.DosSeparator, Folder.UnixSeparator);
}
return path;
}
public static string ApplicationData {
get; private set;
}
public static string ApplicationCache {
get; private set;
}
private static string application_name = null;
public static string ApplicationName {
get {
if (application_name == null) {
throw new ApplicationException ("Paths.ApplicationName must be set first");
}
return application_name;
}
set { application_name = value; InitializePaths (); }
}
private static string user_application_name = null;
public static string UserApplicationName {
get {
var application_name = user_application_name ?? ApplicationName;
if (application_name == null) {
throw new ApplicationException ("Paths.ApplicationName must be set first");
}
return application_name;
}
set { user_application_name = value; }
}
// This can only happen after ApplicationName is set.
private static void InitializePaths ()
{
ApplicationCache = Path.Combine (XdgBaseDirectorySpec.GetUserDirectory (
"XDG_CACHE_HOME", ".cache"), UserApplicationName);
ApplicationData = Path.Combine (Environment.GetFolderPath (
Environment.SpecialFolder.ApplicationData), UserApplicationName);
if (!Directory.Exists (ApplicationData)) {
Directory.CreateDirectory (ApplicationData);
}
}
public static string ExtensionCacheRoot {
get { return Path.Combine (ApplicationCache, "extensions"); }
}
public static string SystemTempDir {
get { return "/tmp/"; }
}
public static string TempDir {
get {
string dir = Path.Combine (ApplicationCache, "temp");
// If this location exists, but as a file not a directory, delete it
if (File.Exists (dir)) {
File.Delete (dir);
}
Directory.CreateDirectory (dir);
return dir;
}
}
private static string installed_application_prefix = null;
public static string InstalledApplicationPrefix {
get {
if (installed_application_prefix == null) {
installed_application_prefix = Path.GetDirectoryName (
System.Reflection.Assembly.GetExecutingAssembly ().Location);
// For Banshee on Linux running uninstalled, share/ is located within the assembly's dir
if (Directory.Exists (Paths.Combine (installed_application_prefix, "share", ApplicationName))) {
return installed_application_prefix;
}
// For Banshee on Windows, share/ is one up from bin/ where the assembly is located
if (Directory.Exists (Paths.Combine (installed_application_prefix, "..", "share", ApplicationName))) {
return installed_application_prefix = new DirectoryInfo (installed_application_prefix).Parent.FullName;
}
DirectoryInfo entry_directory = new DirectoryInfo (installed_application_prefix);
if (entry_directory != null && entry_directory.Parent != null && entry_directory.Parent.Parent != null) {
installed_application_prefix = entry_directory.Parent.Parent.FullName;
}
}
return installed_application_prefix;
}
}
public static string InstalledApplicationDataRoot {
get { return Path.Combine (InstalledApplicationPrefix, "share"); }
}
public static string InstalledApplicationData {
get { return Path.Combine (InstalledApplicationDataRoot, ApplicationName); }
}
public static string GetInstalledDataDirectory (string path)
{
return Path.Combine (InstalledApplicationData, path);
}
}
}
| |
using UnityEngine;
using System.Collections;
public class ScreenWipe : MonoBehaviour
{
public enum ZoomType
{
Grow, Shrink
}
public enum TransitionType
{
Left, Right, Up, Down
}
private Texture tex;
private RenderTexture renderTex;
private Texture2D tex2D;
private float alpha;
private bool reEnableListener;
private Material shapeMaterial;
private Transform shape;
private AnimationCurve curve;
private bool useCurve;
public static ScreenWipe use;
//This is a dumb implementation of singleton
void Awake ()
{
if (use)
{
Debug.LogWarning("Only one instance of ScreenCrossFadePro is allowed");
return;
}
use = this;
this.enabled = false;
}
void OnGUI ()
{
GUI.depth = -9999999;
GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, alpha);
if (tex != null)
GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height), tex);
}
IEnumerator AlphaTimer ( float time )
{
float rate = 1.0f/time;
if( useCurve )
{
float t = 0.0f;
while( t < 1.0f )
{
alpha = curve.Evaluate( t );
t += Time.deltaTime * rate;
yield return 0;
}
}
else
{
for (alpha = 1.0f; alpha > 0.0f; alpha -= Time.deltaTime * rate)
{
yield return 0;
}
}
}
void CameraSetup( Camera cam1, Camera cam2, bool cam1Active, bool enableThis )
{
if (enableThis)
{
this.enabled = true;
}
cam1.gameObject.active = cam1Active;
cam2.gameObject.active = true;
AudioListener listener = cam2.GetComponent<AudioListener>();
if (listener)
{
reEnableListener = listener.enabled? true : false;
listener.enabled = false;
}
}
void CameraCleanup ( Camera cam1, Camera cam2 )
{
AudioListener listener = cam2.GetComponent<AudioListener>();
if (listener && reEnableListener) {
listener.enabled = true;
}
cam1.gameObject.active = false;
this.enabled = false;
}
public IEnumerator CrossFadePro ( Camera cam1, Camera cam2, float time )
{
if (!renderTex)
{
renderTex = new RenderTexture(Screen.width, Screen.height, 24);
}
cam1.targetTexture = renderTex;
tex = renderTex;
CameraSetup (cam1, cam2, true, true);
// Debug.Log("CrossFadePro() begun");
yield return StartCoroutine( AlphaTimer( time ) );
// Debug.Log("CrossFadePro() finished");
cam1.targetTexture = null;
renderTex.Release();
CameraCleanup (cam1, cam2);
}
IEnumerator CrossFade ( Camera cam1, Camera cam2, float time )
{
yield return CrossFade( cam1, cam2, time, null );
}
public IEnumerator CrossFade ( Camera cam1, Camera cam2, float time, AnimationCurve _curve )
{
curve = _curve;
useCurve = curve != null;
if (!tex2D)
{
tex2D = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
}
tex2D.ReadPixels( new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
tex2D.Apply();
tex = tex2D;
yield return 0;
CameraSetup (cam1, cam2, false, true);
yield return AlphaTimer(time);
CameraCleanup (cam1, cam2);
}
IEnumerator RectWipe ( Camera cam1 , Camera cam2 , float time , ZoomType zoom )
{
yield return RectWipe( cam1, cam2, time, zoom, null );
}
public IEnumerator RectWipe ( Camera cam1 , Camera cam2 , float time , ZoomType zoom , AnimationCurve _curve )
{
curve = _curve;
useCurve = curve != null;
CameraSetup (cam1, cam2, true, false);
Camera useCam = (zoom == ZoomType.Shrink)? cam1 : cam2;
Camera otherCam = (zoom == ZoomType.Shrink)? cam2 : cam1;
Rect originalRect = useCam.rect;
float originalDepth = useCam.depth;
useCam.depth = otherCam.depth+1;
if( useCurve )
{
float rate= 1.0f/(time);
if (zoom == ZoomType.Shrink)
{
for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate) {
float t = curve.Evaluate( i )*0.5f;
cam1.rect = new Rect(t, t, 1.0f-t*2, 1.0f-t*2);
yield return 0;
}
}
else
{
for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate) {
float t = curve.Evaluate( i )*0.5f;
cam2.rect = new Rect(.5f - t, .5f - t, t * 2.0f, t * 2.0f);
yield return 0;
}
}
}
else
{
float rate = 1.0f/(time*2);
if (zoom == ZoomType.Shrink)
{
for (float i = 0.0f; i < .5; i += Time.deltaTime * rate)
{
float t = Mathf.Lerp(0.0f, .5f, Mathf.Sin(i * Mathf.PI)); // Slow down near the end
cam1.rect = new Rect(t, t, 1.0f-t*2, 1.0f-t*2);
yield return 0;
}
}
else
{
for (float i = 0.0f; i < .5f; i += Time.deltaTime * rate)
{
float t = Mathf.Lerp(.5f, 0.0f, Mathf.Sin((.5f-i) * Mathf.PI)); // Start out slower
cam2.rect = new Rect(.5f-t, .5f-t, t*2.0f, t*2.0f);
yield return 0;
}
}
}
useCam.rect = originalRect;
useCam.depth = originalDepth;
CameraCleanup (cam1, cam2);
}
IEnumerator ShapeWipe ( Camera cam1 , Camera cam2 , float time , ZoomType zoom , Mesh mesh , float rotateAmount )
{
yield return ShapeWipe( cam1, cam2, time, zoom, mesh, rotateAmount, null );
}
public IEnumerator ShapeWipe ( Camera cam1 , Camera cam2 , float time , ZoomType zoom , Mesh mesh , float rotateAmount , AnimationCurve _curve )
{
curve = _curve;
useCurve = curve != null;
if (!shapeMaterial)
{
shapeMaterial = new Material (
"Shader \"DepthMask\" {" +
" SubShader {" +
" Tags { \"Queue\" = \"Background\" }" +
" Lighting Off ZTest LEqual ZWrite On Cull Off ColorMask 0" +
" Pass {}" +
" }" +
"}"
);
}
if (!shape)
{
GameObject gobjShape = new GameObject("Shape");
gobjShape.AddComponent("MeshFilter");
gobjShape.AddComponent("MeshRenderer");
shape = gobjShape.transform;
shape.renderer.material = shapeMaterial;
}
CameraSetup (cam1, cam2, true, false);
Camera useCam = (zoom == ZoomType.Shrink)? cam1 : cam2;
Camera otherCam = (zoom == ZoomType.Shrink)? cam2 : cam1;
float originalDepth = otherCam.depth;
CameraClearFlags originalClearFlags = otherCam.clearFlags;
otherCam.depth = useCam.depth+1;
otherCam.clearFlags = CameraClearFlags.Depth;
shape.gameObject.active = true;
(shape.GetComponent<MeshFilter>() as MeshFilter).mesh = mesh;
shape.position = otherCam.transform.position + otherCam.transform.forward * (otherCam.nearClipPlane+.01f);
shape.parent = otherCam.transform;
shape.localRotation = Quaternion.identity;
if( useCurve )
{
float rate = 1.0f/time;
if (zoom == ZoomType.Shrink)
{
for (float i = 1.0f; i > 0.0f; i -= Time.deltaTime * rate)
{
float t = curve.Evaluate( i );
shape.localScale = new Vector3(t, t, t);
shape.localEulerAngles = new Vector3(0.0f, 0.0f, i * rotateAmount);
yield return 0;
}
}
else
{
for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate)
{
float t = curve.Evaluate( i );
shape.localScale = new Vector3(t, t, t);
shape.localEulerAngles = new Vector3(0.0f, 0.0f, -i * rotateAmount);
yield return 0;
}
}
}
else{
float rate = 1.0f/time;
if (zoom == ZoomType.Shrink) {
for (float i = 1.0f; i > 0.0f; i -= Time.deltaTime * rate) {
float t = Mathf.Lerp(1.0f, 0.0f, Mathf.Sin((1.0f-i) * Mathf.PI * 0.5f)); // Slow down near the end
shape.localScale = new Vector3(t, t, t);
shape.localEulerAngles = new Vector3(0.0f, 0.0f, i * rotateAmount);
yield return 0;
}
}
else {
for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate) {
float t = Mathf.Lerp(1.0f, 0.0f, Mathf.Sin((1.0f-i) * Mathf.PI * 0.5f)); // Start out slower
shape.localScale = new Vector3(t, t, t);
shape.localEulerAngles = new Vector3(0.0f, 0.0f, -i * rotateAmount);
yield return 0;
}
}
}
otherCam.clearFlags = originalClearFlags;
otherCam.depth = originalDepth;
CameraCleanup (cam1, cam2);
shape.parent = null;
shape.gameObject.active = false;
}
IEnumerator SquishWipe ( Camera cam1 , Camera cam2 , float time , TransitionType transitionType )
{
yield return SquishWipe( cam1, cam2, time, transitionType, null );
}
public IEnumerator SquishWipe ( Camera cam1 , Camera cam2 , float time , TransitionType transitionType , AnimationCurve _curve )
{
curve = _curve;
useCurve = curve != null;
Rect originalCam1Rect = cam1.rect;
Rect originalCam2Rect = cam2.rect;
Matrix4x4 cam1Matrix = cam1.projectionMatrix;
Matrix4x4 cam2Matrix = cam2.projectionMatrix;
CameraSetup (cam1, cam2, true, false);
float rate = 1.0f/time;
float t = 0.0f;
float i = 0.0f;
while( i < 1.0f )
{
if( useCurve )
{
i = curve.Evaluate(t);
t += Time.deltaTime * rate;
}
else
{
i += Time.deltaTime * rate;
}
switch (transitionType)
{
case TransitionType.Right:
cam1.rect = new Rect(i, 0, 1.0f, 1.0f);
cam2.rect = new Rect(0, 0, i, 1.0f);
break;
case TransitionType.Left:
cam1.rect = new Rect(0, 0, 1.0f-i, 1.0f);
cam2.rect = new Rect(1.0f-i, 0, 1.0f, 1.0f);
break;
case TransitionType.Up:
cam1.rect = new Rect(0, i, 1.0f, 1.0f);
cam2.rect = new Rect(0, 0, 1.0f, i);
break;
case TransitionType.Down:
cam1.rect = new Rect(0, 0, 1.0f, 1.0f-i);
cam2.rect = new Rect(0, 1.0f-i, 1.0f, 1.0f);
break;
}
cam1.projectionMatrix = cam1Matrix;
cam2.projectionMatrix = cam2Matrix;
yield return 0;
}
cam1.rect = originalCam1Rect;
cam2.rect = originalCam2Rect;
CameraCleanup (cam1, cam2);
}
public int planeResolution = 90; // Higher numbers make the DreamWipe effect smoother, but take more CPU time
private Vector3[] baseVertices;
private Vector3[] newVertices;
private Material planeMaterial;
private GameObject plane;
private RenderTexture renderTex2;
public void InitializeDreamWipe ()
{
if (planeMaterial && plane) return;
Debug.Log("InitializeDreamWipe here!");
planeMaterial = new Material
(
"Shader \"Unlit2Pass\" {" +
"Properties {" +
" _Color (\"Main Color\", Color) = (1,1,1,1)" +
" _Tex1 (\"Base\", Rect) = \"white\" {}" +
" _Tex2 (\"Base\", Rect) = \"white\" {}" +
"}" +
"Category {" +
" ZWrite Off Alphatest Greater 0 ColorMask RGB Lighting Off" +
" Tags {\"Queue\"=\"Transparent\" \"IgnoreProjector\"=\"True\" \"RenderType\"=\"Transparent\"}" +
" Blend SrcAlpha OneMinusSrcAlpha" +
" SubShader {" +
" Pass {SetTexture [_Tex2]}" +
" Pass {SetTexture [_Tex1] {constantColor [_Color] Combine texture * constant, texture * constant}}" +
" }" +
"}}"
);
// Set up plane object
plane = new GameObject("Plane");
plane.AddComponent("MeshFilter");
plane.AddComponent("MeshRenderer");
plane.renderer.material = planeMaterial;
plane.renderer.castShadows = false;
plane.renderer.receiveShadows = false;
plane.renderer.enabled = false;
// Create the mesh used for the distortion effect
Mesh planeMesh = new Mesh();
(plane.GetComponent<MeshFilter>() as MeshFilter).mesh = planeMesh;
planeResolution = Mathf.Clamp(planeResolution, 1, 16380);
baseVertices = new Vector3[4*planeResolution + 4];
newVertices = new Vector3[baseVertices.Length];
Vector2[] newUV = new Vector2[baseVertices.Length];
int[] newTriangles = new int[18*planeResolution];
int idx = 0;
for (int i = 0; i <= planeResolution; i++)
{
float add = 1.0f/planeResolution*i;
newUV[idx] = new Vector2(0.0f, 1.0f-add);
baseVertices[idx++] = new Vector3(-1.0f, .5f-add, 0.0f);
newUV[idx] = new Vector2(0.0f, 1.0f-add);
baseVertices[idx++] = new Vector3(-.5f, .5f-add, 0.0f);
newUV[idx] = new Vector2(1.0f, 1.0f-add);
baseVertices[idx++] = new Vector3(.5f, .5f-add, 0.0f);
newUV[idx] = new Vector2(1.0f, 1.0f-add);
baseVertices[idx++] = new Vector3(1.0f, .5f-add, 0.0f);
}
idx = 0;
for (int y = 0; y < planeResolution; y++)
{
for (int x = 0; x < 3; x++) {
newTriangles[idx++] = (y*4 )+x;
newTriangles[idx++] = (y*4 )+x+1;
newTriangles[idx++] = ((y+1)*4)+x;
newTriangles[idx++] = ((y+1)*4)+x;
newTriangles[idx++] = (y *4)+x+1;
newTriangles[idx++] = ((y+1)*4)+x+1;
}
}
planeMesh.vertices = baseVertices;
planeMesh.uv = newUV;
planeMesh.triangles = newTriangles;
// Set up rendertextures
renderTex = new RenderTexture(Screen.width, Screen.height, 24);
renderTex2 = new RenderTexture(Screen.width, Screen.height, 24);
renderTex.filterMode = renderTex2.filterMode = FilterMode.Point;
planeMaterial.SetTexture("_Tex1", renderTex);
planeMaterial.SetTexture("_Tex2", renderTex2);
}
// IEnumerator DreamWipe ( Camera cam1 , Camera cam2 , float time )
// {
// yield return DreamWipe (cam1, cam2, time, .07f, 25.0f);
// }
public IEnumerator DreamWipe ( Camera cam1, Camera cam2, float time, float waveScale, float waveFrequency )
{
if (!plane)
{
InitializeDreamWipe();
}
waveScale = Mathf.Clamp(waveScale, -.5f, .5f);
waveFrequency = .25f/(planeResolution/waveFrequency);
CameraSetup (cam1, cam2, true, false);
Debug.Log("DreamWipe() begun");
// Make a camera that will show a plane with the combined rendertextures from cam1 and cam2,
// and make it have the highest depth so it's always on top
Camera cam2Clone = Instantiate(cam2, cam2.transform.position, cam2.transform.rotation) as Camera;
cam2Clone.depth = cam1.depth+1;
if (cam2Clone.depth <= cam2.depth)
{
cam2Clone.depth = cam2.depth+1;
}
// Get screen coodinates of 0,0 in local spatial coordinates, so we know how big to scale the plane (make sure clip planes are reasonable)
cam2Clone.nearClipPlane = .5f;
cam2Clone.farClipPlane = 1.0f;
Vector3 p = cam2Clone.transform.InverseTransformPoint(cam2.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, cam2Clone.nearClipPlane)));
plane.transform.localScale = new Vector3(-p.x*2.0f, -p.y*2.0f, 1.0f);
plane.transform.parent = cam2Clone.transform;
plane.transform.localPosition = plane.transform.localEulerAngles = Vector3.zero;
// Must be a tiny bit beyond the nearClipPlane, or it might not show up
plane.transform.Translate(Vector3.forward * (cam2Clone.nearClipPlane+.00005f));
// Move the camera back so cam2 won't see the renderPlane, and parent it to cam2 so that if cam2 is moving, it won't see the plane
cam2Clone.transform.Translate(Vector3.forward * -1.0f);
cam2Clone.transform.parent = cam2.transform;
// Initialize some stuff
plane.renderer.enabled = true;
float scale = 0.0f;
Mesh planeMesh = plane.GetComponent<MeshFilter>().mesh;
cam1.targetTexture = renderTex;
cam2.targetTexture = renderTex2;
// Do the cross-fade
float rate = 1.0f/time;
for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate)
{
planeMaterial.color = new Color( planeMaterial.color.r, planeMaterial.color.g, planeMaterial.color.b, Mathf.SmoothStep(0.0f, 1.0f, Mathf.InverseLerp(.75f, .15f, i)));
// Make plane undulate
for (int j = 0; j < newVertices.Length; j++) {
newVertices[j] = baseVertices[j];
newVertices[j].x += Mathf.Sin(j*waveFrequency + i*time) * scale;
}
planeMesh.vertices = newVertices;
scale = Mathf.Sin(Mathf.PI * Mathf.SmoothStep(0.0f, 1.0f, i)) * waveScale;
yield return 0;
}
Debug.Log("DreamWipe() finished");
// Clean up
CameraCleanup (cam1, cam2);
plane.renderer.enabled = false;
plane.transform.parent = null;
Destroy(cam2Clone.gameObject);
cam1.targetTexture = cam2.targetTexture = null;
renderTex.Release();
renderTex2.Release();
}
}
| |
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using skadisteam.login.Constants;
using skadisteam.login.Http.Headers;
using skadisteam.login.Models;
using skadisteam.login.Models.Json;
using skadisteam.login.Factories;
using skadisteam.login.Http;
using skadisteam.login.Validators;
using skadisteam.shared.Models;
namespace skadisteam.login
{
/// <summary>
/// Class which has the required methods to make
/// a login into the steamcommunity.
/// </summary>
public class SkadiLogin
{
private RequestFactory _requestFactory;
private SkadiLoginConfiguration _skadiLoginConfiguration;
/// <summary>
/// Standard constructor. When used this the default settings are used.
/// These are:
/// <list type="table">
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>StopOnError</term>
/// <description>true</description>
/// </item>
/// <item>
/// <term>WaitTimeEachError</term>
/// <description>5</description>
/// </item>
/// </list>
/// For more information lookup: <see cref="SkadiLoginConfiguration"/>.
/// </summary>
public SkadiLogin()
{
_requestFactory = new RequestFactory();
}
/// <summary>
/// Constructor which takes a <see cref="SkadiLoginConfiguration"/>.
/// You can edit the default behaviour there.
/// </summary>
/// <param name="skadiLoginConfiguration">
/// Login configuration which should be used.
/// See: <see cref="SkadiLoginConfiguration"/>.
/// </param>
public SkadiLogin(SkadiLoginConfiguration skadiLoginConfiguration)
{
_requestFactory = new RequestFactory();
_skadiLoginConfiguration = skadiLoginConfiguration;
}
/// <summary>
/// Execute the login. This will take the configuration into consideration
/// which can be given as parameter in the constructor.
/// </summary>
/// <param name="skadiLoginData">
/// Date of the steam login. See <see cref="SkadiLoginData"/>.
/// </param>
/// <returns>
/// It will return a response with login data.
/// For more information lookup <see cref="SkadiLoginResponse"/>.
/// </returns>
public SkadiLoginResponse Execute(SkadiLoginData skadiLoginData)
{
GetSession();
if (_skadiLoginConfiguration != null &&
!_skadiLoginConfiguration.StopOnError)
{
return ExecuteUntilLogin(skadiLoginData);
}
var rsaKey = GetRsaKey(skadiLoginData.Username);
var doLoginResponse = DoLogin(rsaKey, skadiLoginData.Username,
skadiLoginData.Password, skadiLoginData.SharedSecret);
if (!DoLoginResponseValidator.IsValid(doLoginResponse))
{
SkadiLoginResponse skadiLoginResponse = new SkadiLoginResponse();
skadiLoginResponse.SkadiLoginError =
SkadiLoginErrorFactory.Create(doLoginResponse);
return skadiLoginResponse;
}
Transfer(doLoginResponse);
return SetSession();
}
private SkadiLoginResponse ExecuteUntilLogin(SkadiLoginData skadiLoginData)
{
GetSession();
GetRsaKeyResponse rsaKey = new GetRsaKeyResponse();
DoLoginResponse doLoginResponse = new DoLoginResponse();
var doLoginSuccessful = false;
do
{
try
{
rsaKey = GetRsaKey(skadiLoginData.Username);
doLoginResponse = DoLogin(rsaKey, skadiLoginData.Username,
skadiLoginData.Password, skadiLoginData.SharedSecret);
if (!DoLoginResponseValidator.IsValid(doLoginResponse))
{
if (doLoginResponse.CaptchaNeeded)
{
// TODO: Get exact time for cooldown of captcha!
Task.Delay(TimeSpan.FromMinutes(25));
}
rsaKey = null;
doLoginResponse = null;
}
else
{
doLoginSuccessful = true;
}
}
catch (Exception)
{
Task.Delay(
TimeSpan.FromSeconds(
_skadiLoginConfiguration.WaitTimeEachError)).Wait();
}
}
while (doLoginSuccessful == false);
bool errorInTransfer = false;
do
{
try
{
Transfer(doLoginResponse);
}
catch (Exception)
{
errorInTransfer = true;
Task.Delay(TimeSpan.FromSeconds(5)).Wait();
}
} while (errorInTransfer);
SkadiLoginResponse skadiLoginResponse = null;
do
{
try
{
skadiLoginResponse = SetSession();
}
catch (Exception)
{
Task.Delay(TimeSpan.FromSeconds(5)).Wait();
}
} while (skadiLoginResponse == null);
return skadiLoginResponse;
}
private void GetSession()
{
_requestFactory.CreateSession();
}
private GetRsaKeyResponse GetRsaKey(string username)
{
var postContent = PostDataFactory.CreateGetRsaKeyData(username);
GetRsaKeyResponse getRsaKeyResponse = null;
var response = _requestFactory.Create(HttpMethod.POST,
Uris.SteamCommunitySecureBase,
SteamCommunityEndpoints.GetRsaKey, Accept.All,
HttpHeaderValues.AcceptLanguageOne, false, true, true, true,
false, postContent);
string responseContent = response.Content.ReadAsStringAsync().Result;
getRsaKeyResponse =
JsonConvert.DeserializeObject<GetRsaKeyResponse>(responseContent);
return getRsaKeyResponse;
}
private DoLoginResponse DoLogin(GetRsaKeyResponse getRsaKeyResponse,
string username, string password, string sharedSecret)
{
DoLoginResponse doLoginResponse = null;
var encryptedPassword = EncryptPasswordFactory.Create(getRsaKeyResponse, password);
var content = PostDataFactory.CreateDoLoginData(username,
encryptedPassword, getRsaKeyResponse.Timestamp,
TwoFactorCodeFactory.Create(sharedSecret));
var response = _requestFactory.Create(HttpMethod.POST,
Uris.SteamCommunitySecureBase,
SteamCommunityEndpoints.DoLogin, Accept.All,
HttpHeaderValues.AcceptLanguageOne, false, true, true, true,
false, content);
string responseContent = response.Content.ReadAsStringAsync().Result;
doLoginResponse =
JsonConvert.DeserializeObject<DoLoginResponse>(responseContent);
return doLoginResponse;
}
private void Transfer(DoLoginResponse doLoginResponse)
{
var content = PostDataFactory.CreateTransferData(doLoginResponse);
_requestFactory.Create(HttpMethod.POST,
Uris.HelpSteampoweredSecureBase,
HelpSteampoweredEndpoints.TransferLogin,
Accept.Html, HttpHeaderValues.AcceptLanguageTwo, true, true,
true, false, true, content);
}
private SkadiLoginResponse SetSession()
{
var response = _requestFactory.Create(HttpMethod.GET,
Uris.SteamCommunityBase, SteamCommunityEndpoints.Home,
Accept.Html, HttpHeaderValues.AcceptLanguageTwo, true, false,
false, false, false, null);
return SkadiLoginResponseFactory.Create(response, _requestFactory.GetCookieContainer());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
#if MAGICONION_UNITASK_SUPPORT
using Cysharp.Threading.Tasks;
using Channel = Grpc.Core.Channel;
#endif
using Grpc.Core;
#if USE_GRPC_NET_CLIENT
using Grpc.Net.Client;
#endif
using MagicOnion.Client;
using UnityEditor;
using UnityEngine;
namespace MagicOnion.Unity.Editor
{
public class GrpcChannelProviderMonitor
{
private readonly Dictionary<int, bool> _stackTraceFoldout = new Dictionary<int, bool>();
private readonly Dictionary<int, bool> _channelOptionsFoldout = new Dictionary<int, bool>();
private readonly Dictionary<GrpcChannelx, DataRatePoints> _historyByChannel = new Dictionary<GrpcChannelx, DataRatePoints>();
private readonly IGrpcChannelProvider _provider;
private DateTime _lastUpdatedAt;
public GrpcChannelProviderMonitor(IGrpcChannelProvider provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}
public bool TryUpdate()
{
if ((DateTime.Now - _lastUpdatedAt).TotalSeconds >= 1)
{
foreach (var channel in _provider.GetAllChannels())
{
if (!_historyByChannel.TryGetValue(channel, out var history))
{
_historyByChannel[channel] = history = new DataRatePoints();
}
var diagInfo = ((IGrpcChannelxDiagnosticsInfo) channel);
history.AddValues(diagInfo.Stats.ReceiveBytesPerSecond, diagInfo.Stats.SentBytesPerSecond);
}
_lastUpdatedAt = DateTime.Now;
return true;
}
return false;
}
public void DrawChannels()
{
var channels = _provider.GetAllChannels();
if (!channels.Any())
{
EditorGUILayout.HelpBox("The application has no gRPC channel yet.", MessageType.Info);
return;
}
foreach (var channel in channels)
{
var diagInfo = ((IGrpcChannelxDiagnosticsInfo)channel);
if (!_historyByChannel.TryGetValue(channel, out var history))
{
_historyByChannel[channel] = history = new DataRatePoints();
}
using (new Section(() =>
{
using (new EditorGUILayout.HorizontalScope())
{
#if !USE_GRPC_NET_CLIENT_ONLY
if (diagInfo.UnderlyingChannel is Channel grpcCCoreChannel)
{
EditorGUILayout.LabelField($"Channel: {channel.Id} ({channel.Target}; State={grpcCCoreChannel.State})", EditorStyles.boldLabel);
}
else
#endif
{
EditorGUILayout.LabelField($"Channel: {channel.Id} ({channel.Target})", EditorStyles.boldLabel);
}
if (GUILayout.Button("...", GUILayout.ExpandWidth(false)))
{
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Disconnect"), false, x => { ((GrpcChannelx)x).Dispose(); }, channel);
menu.ShowAsContext();
}
}
}))
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.LabelField("Total Received Bytes", diagInfo.Stats.ReceivedBytes.ToString("#,0") + " bytes");
EditorGUILayout.LabelField("Total Sent Bytes", diagInfo.Stats.SentBytes.ToString("#,0") + " bytes");
}
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.LabelField("Received Bytes/Sec", diagInfo.Stats.ReceiveBytesPerSecond.ToString("#,0") + " bytes/s");
EditorGUILayout.LabelField("Sent Bytes/Sec", diagInfo.Stats.SentBytesPerSecond.ToString("#,0") + " bytes/s");
}
DrawChart(channel, history);
var streamingHubs = ((IMagicOnionAwareGrpcChannel)channel).GetAllManagedStreamingHubs();
if (streamingHubs.Any())
{
using (new Section("StreamingHubs"))
{
foreach (var streamingHub in streamingHubs)
{
EditorGUILayout.LabelField(streamingHub.StreamingHubType.FullName);
EditorGUI.indentLevel++;
EditorGUILayout.LabelField(streamingHub.Client.GetType().FullName);
EditorGUI.indentLevel--;
}
}
}
if (_stackTraceFoldout[channel.Id] = EditorGUILayout.Foldout(_stackTraceFoldout.TryGetValue(channel.Id, out var foldout) ? foldout : false, "StackTrace"))
{
var reducedStackTrace = string.Join("\n", diagInfo.StackTrace
.Split('\n')
.SkipWhile(x => x.StartsWith($" at {typeof(GrpcChannelx).FullName}"))
.Where(x => !x.StartsWith(" at System.Runtime.CompilerServices."))
.Where(x => !x.StartsWith(" at System.Threading.ExecutionContext."))
.Where(x => !x.StartsWith(" at Cysharp.Threading.Tasks.CompilerServices."))
.Where(x => !x.StartsWith(" at Cysharp.Threading.Tasks.AwaiterActions."))
.Where(x => !x.StartsWith(" at Cysharp.Threading.Tasks.UniTask"))
.Where(x => !x.StartsWith(" at MagicOnion.Unity.GrpcChannelProviderExtensions."))
);
EditorGUILayout.TextArea(reducedStackTrace, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 40));
}
if (_channelOptionsFoldout[channel.Id] = EditorGUILayout.Foldout(_channelOptionsFoldout.TryGetValue(channel.Id, out var channelOptionsFoldout) ? channelOptionsFoldout : false, "ChannelOptions"))
{
using (new EditorGUI.DisabledGroupScope(true))
{
var prevLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 350;
foreach (var keyValue in diagInfo.ChannelOptions.GetValues())
{
if (keyValue.Value is int intValue)
{
EditorGUILayout.IntField(keyValue.Key, intValue);
}
else if (keyValue.Value is long longValue)
{
EditorGUILayout.LongField(keyValue.Key, longValue);
}
else
{
EditorGUILayout.TextField(keyValue.Key, keyValue.Value?.ToString() ?? "");
}
}
EditorGUIUtility.labelWidth = prevLabelWidth;
}
}
}
}
}
private void DrawChart(GrpcChannelx channel, DataRatePoints history)
{
// Draw Chart
var prevHandlesColor = Handles.color;
{
var rect = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(GUILayoutUtility.GetLastRect().width, 100));
Handles.DrawSolidRectangleWithOutline(rect, Color.black, Color.gray);
var drawableRect = new Rect(rect.x + 2, rect.y + 2, rect.width - 4, rect.height - 4);
var maxCount = 60;
var maxY = DataUnit.GetScaleMaxValue(Math.Max(history.ReceivedValues.DefaultIfEmpty().Max(), history.SentValues.DefaultIfEmpty().Max()));
var dx = drawableRect.width / (float)(maxCount - 1);
var dy = drawableRect.height / (float)maxY;
// Grid (9 lines)
Handles.color = new Color(0.05f, 0.25f, 0.05f);
for (var i = 1; i < 10; i++)
{
var yTop = drawableRect.y + (drawableRect.height / 10) * i;
Handles.DrawLine(new Vector3(drawableRect.x, yTop), new Vector3(drawableRect.xMax, yTop));
}
// Label
Handles.Label(new Vector3(drawableRect.x, drawableRect.y), DataUnit.Humanize(maxY) + " bytes/sec");
// Values
Span<int> buffer = stackalloc int[60];
var points = new List<Vector3>();
{
var values = history.ReceivedValues.ToSpan(buffer);
for (var i = 0; i < Math.Min(maxCount, values.Length); i++)
{
var p = new Vector3(drawableRect.x + (drawableRect.width - (dx * i)), drawableRect.yMax - (dy * values[values.Length - i - 1]));
points.Add(p);
}
Handles.color = new Color(0.33f, 0.55f, 0.33f);
Handles.DrawAAPolyLine(4f, points.ToArray());
}
points.Clear();
{
var values = history.SentValues.ToSpan(buffer);
for (var i = 0; i < Math.Min(maxCount, values.Length); i++)
{
var p = new Vector3(drawableRect.x + (drawableRect.width - (dx * i)), drawableRect.yMax - (dy * values[values.Length - i - 1]));
points.Add(p);
}
Handles.color = new Color(0.2f, 0.33f, 0.2f);
Handles.DrawAAPolyLine(2f, points.ToArray());
}
}
Handles.color = prevHandlesColor;
}
private class DataRatePoints
{
public RingBuffer<int> ReceivedValues { get; }
public RingBuffer<int> SentValues { get; }
public DataRatePoints()
{
ReceivedValues = new RingBuffer<int>(60);
SentValues = new RingBuffer<int>(60);
}
public void AddValues(int receivedBytesPerSecond, int sentBytesPerSecond)
{
ReceivedValues.Add(receivedBytesPerSecond);
SentValues.Add(sentBytesPerSecond);
}
}
private struct Section : IDisposable
{
public Section(string label)
{
if (!string.IsNullOrWhiteSpace(label))
{
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
}
EditorGUI.indentLevel++;
}
public Section(Action action)
{
action();
EditorGUI.indentLevel++;
}
public void Dispose()
{
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
}
}
private class RingBuffer<T> : IEnumerable<T>
{
private readonly T[] _buffer;
private int _index = 0;
private bool IsFull => _index > _buffer.Length;
private int StartIndex => IsFull ? _index % _buffer.Length : 0;
public int Length => IsFull ? _buffer.Length : _index;
public RingBuffer(int bufferSize)
{
_buffer = new T[bufferSize];
}
public void Add(T item)
{
_buffer[_index++ % _buffer.Length] = item;
}
public Span<T> ToSpan(Span<T> buffer)
{
var index = 0;
foreach (var value in this)
{
buffer[index++] = value;
}
return buffer.Slice(0, index);
}
public Enumerator GetEnumerator()
=> new Enumerator(_buffer, _index, Length);
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _buffer;
private readonly int _start;
private readonly int _length;
private int _current;
public Enumerator(T[] buffer, int start, int length)
{
_buffer = buffer;
_start = start;
_length = length;
_current = -1;
}
public T Current => _buffer[(_start + _current) % _length];
object IEnumerator.Current => Current;
public void Dispose()
{
}
public bool MoveNext()
{
_current++;
return (_current < _length);
}
public void Reset()
{
_current = -1;
}
}
}
private class DataUnit
{
private static readonly long[] _scales = new long[]
{
1_000, // 1 K
10_000, // 10 K
100_000, // 100 K
500_000, // 500 K
1_000_000, // 1 M
2_000_000, // 2 M
10_000_000, // 10 M
20_000_000, // 20 M
100_000_000, // 100 M
200_000_000, // 200 M
500_000_000, // 500 M
1_000_000_000, // 1 G
10_000_000_000, // 10 G
20_000_000_000, // 20 G
50_000_000_000, // 10 G
100_000_000_000, // 100 G
};
public static long GetScaleMaxValue(long value)
{
foreach (var scale in _scales)
{
if (value < scale)
{
return scale;
}
}
return value;
}
public static string Humanize(long value)
{
if (value <= 1_000)
{
return value.ToString("#,0");
}
else if (value <= 1_000_000)
{
return (value / 1_000).ToString("#,0") + " K"; // K
}
else if (value <= 1_000_000_000)
{
return (value / 1_000_000).ToString("#,0") + " M"; // M
}
else if (value <= 1_000_000_000_000)
{
return (value / 1_000_000_000).ToString("#,0") + " G"; // G
}
else
{
return (value / 1_000_000_000_000).ToString("#,0") + " T"; // T
}
}
}
}
}
| |
/*
* 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.Net;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data.Null;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.Avatar.Gods;
using OpenSim.Region.CoreModules.Asset;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence;
using OpenSim.Region.PhysicsModule.BasicPhysics;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Tests.Common
{
/// <summary>
/// Helpers for setting up scenes.
/// </summary>
public class SceneHelpers
{
/// <summary>
/// We need a scene manager so that test clients can retrieve a scene when performing teleport tests.
/// </summary>
public SceneManager SceneManager { get; private set; }
public ISimulationDataService SimDataService { get; private set; }
private AgentCircuitManager m_acm = new AgentCircuitManager();
private IEstateDataService m_estateDataService = null;
private LocalAssetServicesConnector m_assetService;
private LocalAuthenticationServicesConnector m_authenticationService;
private LocalInventoryServicesConnector m_inventoryService;
private LocalGridServicesConnector m_gridService;
private LocalUserAccountServicesConnector m_userAccountService;
private LocalPresenceServicesConnector m_presenceService;
private CoreAssetCache m_cache;
private PhysicsScene m_physicsScene;
public SceneHelpers() : this(null) {}
public SceneHelpers(CoreAssetCache cache)
{
SceneManager = new SceneManager();
m_assetService = StartAssetService(cache);
m_authenticationService = StartAuthenticationService();
m_inventoryService = StartInventoryService();
m_gridService = StartGridService();
m_userAccountService = StartUserAccountService();
m_presenceService = StartPresenceService();
m_inventoryService.PostInitialise();
m_assetService.PostInitialise();
m_userAccountService.PostInitialise();
m_presenceService.PostInitialise();
m_cache = cache;
m_physicsScene = StartPhysicsScene();
SimDataService
= OpenSim.Server.Base.ServerUtils.LoadPlugin<ISimulationDataService>("OpenSim.Tests.Common.dll", null);
}
/// <summary>
/// Set up a test scene
/// </summary>
/// <remarks>
/// Automatically starts services, as would the normal runtime.
/// </remarks>
/// <returns></returns>
public TestScene SetupScene()
{
return SetupScene("Unit test region", UUID.Random(), 1000, 1000);
}
public TestScene SetupScene(string name, UUID id, uint x, uint y)
{
return SetupScene(name, id, x, y, new IniConfigSource());
}
public TestScene SetupScene(string name, UUID id, uint x, uint y, IConfigSource configSource)
{
return SetupScene(name, id, x, y, Constants.RegionSize, Constants.RegionSize, configSource);
}
/// <summary>
/// Set up a scene.
/// </summary>
/// <param name="name">Name of the region</param>
/// <param name="id">ID of the region</param>
/// <param name="x">X co-ordinate of the region</param>
/// <param name="y">Y co-ordinate of the region</param>
/// <param name="sizeX">X size of scene</param>
/// <param name="sizeY">Y size of scene</param>
/// <param name="configSource"></param>
/// <returns></returns>
public TestScene SetupScene(
string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource)
{
Console.WriteLine("Setting up test scene {0}", name);
// We must set up a console otherwise setup of some modules may fail
MainConsole.Instance = new MockConsole();
RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1");
regInfo.RegionName = name;
regInfo.RegionID = id;
regInfo.RegionSizeX = sizeX;
regInfo.RegionSizeY = sizeY;
TestScene testScene = new TestScene(
regInfo, m_acm, SimDataService, m_estateDataService, configSource, null);
INonSharedRegionModule godsModule = new GodsModule();
godsModule.Initialise(new IniConfigSource());
godsModule.AddRegion(testScene);
// Add scene to physics
((INonSharedRegionModule)m_physicsScene).AddRegion(testScene);
((INonSharedRegionModule)m_physicsScene).RegionLoaded(testScene);
// Add scene to services
m_assetService.AddRegion(testScene);
if (m_cache != null)
{
m_cache.AddRegion(testScene);
m_cache.RegionLoaded(testScene);
testScene.AddRegionModule(m_cache.Name, m_cache);
}
m_assetService.RegionLoaded(testScene);
testScene.AddRegionModule(m_assetService.Name, m_assetService);
m_authenticationService.AddRegion(testScene);
m_authenticationService.RegionLoaded(testScene);
testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService);
m_inventoryService.AddRegion(testScene);
m_inventoryService.RegionLoaded(testScene);
testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService);
m_gridService.AddRegion(testScene);
m_gridService.RegionLoaded(testScene);
testScene.AddRegionModule(m_gridService.Name, m_gridService);
m_userAccountService.AddRegion(testScene);
m_userAccountService.RegionLoaded(testScene);
testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService);
m_presenceService.AddRegion(testScene);
m_presenceService.RegionLoaded(testScene);
testScene.AddRegionModule(m_presenceService.Name, m_presenceService);
testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random();
testScene.SetModuleInterfaces();
testScene.LandChannel = new TestLandChannel(testScene);
testScene.LoadWorldMap();
testScene.RegionInfo.EstateSettings = new EstateSettings();
testScene.LoginsEnabled = true;
testScene.RegisterRegionWithGrid();
SceneManager.Add(testScene);
return testScene;
}
private static LocalAssetServicesConnector StartAssetService(CoreAssetCache cache)
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector");
config.AddConfig("AssetService");
config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService");
config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
LocalAssetServicesConnector assetService = new LocalAssetServicesConnector();
assetService.Initialise(config);
if (cache != null)
{
IConfigSource cacheConfig = new IniConfigSource();
cacheConfig.AddConfig("Modules");
cacheConfig.Configs["Modules"].Set("AssetCaching", "CoreAssetCache");
cacheConfig.AddConfig("AssetCache");
cache.Initialise(cacheConfig);
}
return assetService;
}
private static LocalAuthenticationServicesConnector StartAuthenticationService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("AuthenticationService");
config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector");
config.Configs["AuthenticationService"].Set(
"LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService");
config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
LocalAuthenticationServicesConnector service = new LocalAuthenticationServicesConnector();
service.Initialise(config);
return service;
}
private static LocalInventoryServicesConnector StartInventoryService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("InventoryService");
config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector");
config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:XInventoryService");
config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector();
inventoryService.Initialise(config);
return inventoryService;
}
private static LocalGridServicesConnector StartGridService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("GridService");
config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData");
config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
config.Configs["GridService"].Set("ConnectionString", "!static");
LocalGridServicesConnector gridService = new LocalGridServicesConnector();
gridService.Initialise(config);
return gridService;
}
/// <summary>
/// Start a user account service
/// </summary>
/// <param name="testScene"></param>
/// <returns></returns>
private static LocalUserAccountServicesConnector StartUserAccountService()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("UserAccountService");
config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector");
config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
config.Configs["UserAccountService"].Set(
"LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService");
LocalUserAccountServicesConnector userAccountService = new LocalUserAccountServicesConnector();
userAccountService.Initialise(config);
return userAccountService;
}
/// <summary>
/// Start a presence service
/// </summary>
/// <param name="testScene"></param>
private static LocalPresenceServicesConnector StartPresenceService()
{
// Unfortunately, some services share data via statics, so we need to null every time to stop interference
// between tests.
// This is a massive non-obvious pita.
NullPresenceData.Instance = null;
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("PresenceService");
config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector");
config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
config.Configs["PresenceService"].Set(
"LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService");
LocalPresenceServicesConnector presenceService = new LocalPresenceServicesConnector();
presenceService.Initialise(config);
return presenceService;
}
private static PhysicsScene StartPhysicsScene()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Startup");
config.Configs["Startup"].Set("physics", "basicphysics");
PhysicsScene pScene = new BasicScene();
INonSharedRegionModule mod = pScene as INonSharedRegionModule;
mod.Initialise(config);
return pScene;
}
/// <summary>
/// Setup modules for a scene using their default settings.
/// </summary>
/// <param name="scene"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene scene, params object[] modules)
{
SetupSceneModules(scene, new IniConfigSource(), modules);
}
/// <summary>
/// Setup modules for a scene.
/// </summary>
/// <remarks>
/// If called directly, then all the modules must be shared modules.
/// </remarks>
/// <param name="scenes"></param>
/// <param name="config"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene scene, IConfigSource config, params object[] modules)
{
SetupSceneModules(new Scene[] { scene }, config, modules);
}
/// <summary>
/// Setup modules for a scene using their default settings.
/// </summary>
/// <param name="scenes"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene[] scenes, params object[] modules)
{
SetupSceneModules(scenes, new IniConfigSource(), modules);
}
/// <summary>
/// Setup modules for scenes.
/// </summary>
/// <remarks>
/// If called directly, then all the modules must be shared modules.
///
/// We are emulating here the normal calls made to setup region modules
/// (Initialise(), PostInitialise(), AddRegion, RegionLoaded()).
/// TODO: Need to reuse normal runtime module code.
/// </remarks>
/// <param name="scenes"></param>
/// <param name="config"></param>
/// <param name="modules"></param>
public static void SetupSceneModules(Scene[] scenes, IConfigSource config, params object[] modules)
{
List<IRegionModuleBase> newModules = new List<IRegionModuleBase>();
foreach (object module in modules)
{
IRegionModuleBase m = (IRegionModuleBase)module;
// Console.WriteLine("MODULE {0}", m.Name);
m.Initialise(config);
newModules.Add(m);
}
foreach (IRegionModuleBase module in newModules)
{
if (module is ISharedRegionModule) ((ISharedRegionModule)module).PostInitialise();
}
foreach (IRegionModuleBase module in newModules)
{
foreach (Scene scene in scenes)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
}
// RegionLoaded is fired after all modules have been appropriately added to all scenes
foreach (IRegionModuleBase module in newModules)
foreach (Scene scene in scenes)
module.RegionLoaded(scene);
foreach (Scene scene in scenes) { scene.SetModuleInterfaces(); }
}
/// <summary>
/// Generate some standard agent connection data.
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
public static AgentCircuitData GenerateAgentData(UUID agentId)
{
AgentCircuitData acd = GenerateCommonAgentData();
acd.AgentID = agentId;
acd.firstname = "testfirstname";
acd.lastname = "testlastname";
acd.ServiceURLs = new Dictionary<string, object>();
return acd;
}
/// <summary>
/// Generate some standard agent connection data.
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
public static AgentCircuitData GenerateAgentData(UserAccount ua)
{
AgentCircuitData acd = GenerateCommonAgentData();
acd.AgentID = ua.PrincipalID;
acd.firstname = ua.FirstName;
acd.lastname = ua.LastName;
acd.ServiceURLs = ua.ServiceURLs;
return acd;
}
private static AgentCircuitData GenerateCommonAgentData()
{
AgentCircuitData acd = new AgentCircuitData();
// XXX: Sessions must be unique, otherwise one presence can overwrite another in NullPresenceData.
acd.SessionID = UUID.Random();
acd.SecureSessionID = UUID.Random();
acd.circuitcode = 123;
acd.BaseFolder = UUID.Zero;
acd.InventoryFolder = UUID.Zero;
acd.startpos = Vector3.Zero;
acd.CapsPath = "http://wibble.com";
acd.Appearance = new AvatarAppearance();
return acd;
}
/// <summary>
/// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test
/// </summary>
/// <remarks>
/// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will
/// make the agent circuit data (e.g. first, lastname) consistent with the user account data.
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentId"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, UUID agentId)
{
return AddScenePresence(scene, GenerateAgentData(agentId));
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <param name="scene"></param>
/// <param name="ua"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, UserAccount ua)
{
return AddScenePresence(scene, GenerateAgentData(ua));
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <remarks>
/// This function
///
/// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
/// userserver if grid) would give initial login data back to the client and separately tell the scene that the
/// agent was coming.
///
/// 2) Connects the agent with the scene
///
/// This function performs actions equivalent with notifying the scene that an agent is
/// coming and then actually connecting the agent to the scene. The one step missed out is the very first
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentData"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData)
{
return AddScenePresence(scene, new TestClient(agentData, scene), agentData);
}
/// <summary>
/// Add a root agent.
/// </summary>
/// <remarks>
/// This function
///
/// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
/// userserver if grid) would give initial login data back to the client and separately tell the scene that the
/// agent was coming.
///
/// 2) Connects the agent with the scene
///
/// This function performs actions equivalent with notifying the scene that an agent is
/// coming and then actually connecting the agent to the scene. The one step missed out is the very first
/// </remarks>
/// <param name="scene"></param>
/// <param name="agentData"></param>
/// <returns></returns>
public static ScenePresence AddScenePresence(
Scene scene, IClientAPI client, AgentCircuitData agentData)
{
// We emulate the proper login sequence here by doing things in four stages
// Stage 0: login
// We need to punch through to the underlying service because scene will not, correctly, let us call it
// through it's reference to the LPSC
LocalPresenceServicesConnector lpsc = (LocalPresenceServicesConnector)scene.PresenceService;
lpsc.m_PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID);
// Stages 1 & 2
ScenePresence sp = IntroduceClientToScene(scene, client, agentData, TeleportFlags.ViaLogin);
// Stage 3: Complete the entrance into the region. This converts the child agent into a root agent.
sp.CompleteMovement(sp.ControllingClient, true);
return sp;
}
/// <summary>
/// Introduce an agent into the scene by adding a new client.
/// </summary>
/// <returns>The scene presence added</returns>
/// <param name='scene'></param>
/// <param name='testClient'></param>
/// <param name='agentData'></param>
/// <param name='tf'></param>
private static ScenePresence IntroduceClientToScene(
Scene scene, IClientAPI client, AgentCircuitData agentData, TeleportFlags tf)
{
string reason;
// Stage 1: tell the scene to expect a new user connection
if (!scene.NewUserConnection(agentData, (uint)tf, null, out reason))
Console.WriteLine("NewUserConnection failed: " + reason);
// Stage 2: add the new client as a child agent to the scene
scene.AddNewAgent(client, PresenceType.User);
return scene.GetScenePresence(client.AgentId);
}
public static ScenePresence AddChildScenePresence(Scene scene, UUID agentId)
{
return AddChildScenePresence(scene, GenerateAgentData(agentId));
}
public static ScenePresence AddChildScenePresence(Scene scene, AgentCircuitData acd)
{
acd.child = true;
// XXX: ViaLogin may not be correct for child agents
TestClient client = new TestClient(acd, scene);
return IntroduceClientToScene(scene, client, acd, TeleportFlags.ViaLogin);
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene)
{
return AddSceneObject(scene, "Test Object", UUID.Zero);
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <param name="name"></param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene, string name, UUID ownerId)
{
SceneObjectGroup so = new SceneObjectGroup(CreateSceneObjectPart(name, UUID.Random(), ownerId));
//part.UpdatePrimFlags(false, false, true);
//part.ObjectFlags |= (uint)PrimFlags.Phantom;
scene.AddNewSceneObject(so, true);
return so;
}
/// <summary>
/// Add a test object
/// </summary>
/// <param name="scene"></param>
/// <param name="parts">
/// The number of parts that should be in the scene object
/// </param>
/// <param name="ownerId"></param>
/// <param name="partNamePrefix">
/// The prefix to be given to part names. This will be suffixed with "Part<part no>"
/// (e.g. mynamePart1 for the root part)
/// </param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup AddSceneObject(Scene scene, int parts, UUID ownerId, string partNamePrefix, int uuidTail)
{
SceneObjectGroup so = CreateSceneObject(parts, ownerId, partNamePrefix, uuidTail);
scene.AddNewSceneObject(so, false);
return so;
}
/// <summary>
/// Create a scene object part.
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectPart CreateSceneObjectPart(string name, UUID id, UUID ownerId)
{
return new SceneObjectPart(
ownerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = name, UUID = id, Scale = new Vector3(1, 1, 1) };
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <remarks>
/// UUID always starts at 00000000-0000-0000-0000-000000000001. For some purposes, (e.g. serializing direct
/// to another object's inventory) we do not need a scene unique ID. So it would be better to add the
/// UUID when we actually add an object to a scene rather than on creation.
/// </remarks>
/// <param name="parts">The number of parts that should be in the scene object</param>
/// <param name="ownerId"></param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId)
{
return CreateSceneObject(parts, ownerId, 0x1);
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <param name="parts">The number of parts that should be in the scene object</param>
/// <param name="ownerId"></param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, int uuidTail)
{
return CreateSceneObject(parts, ownerId, "", uuidTail);
}
/// <summary>
/// Create a scene object but do not add it to the scene.
/// </summary>
/// <param name="parts">
/// The number of parts that should be in the scene object
/// </param>
/// <param name="ownerId"></param>
/// <param name="partNamePrefix">
/// The prefix to be given to part names. This will be suffixed with "Part<part no>"
/// (e.g. mynamePart1 for the root part)
/// </param>
/// <param name="uuidTail">
/// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
/// will be given to the root part, and incremented for each part thereafter.
/// </param>
/// <returns></returns>
public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, string partNamePrefix, int uuidTail)
{
string rawSogId = string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail);
SceneObjectGroup sog
= new SceneObjectGroup(
CreateSceneObjectPart(string.Format("{0}Part1", partNamePrefix), new UUID(rawSogId), ownerId));
if (parts > 1)
for (int i = 2; i <= parts; i++)
sog.AddPart(
CreateSceneObjectPart(
string.Format("{0}Part{1}", partNamePrefix, i),
new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail + i - 1)),
ownerId));
return sog;
}
}
}
| |
// KeyTime.cs
// Allow suppression of certain presharp messages
#pragma warning disable 1634, 1691
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media.Animation
{
/// <summary>
/// A KeyTime is use to specify when relative to the time of an animation
/// that a KeyFrame takes place.
/// </summary>
[TypeConverter(typeof(KeyTimeConverter))]
public struct KeyTime : IEquatable<KeyTime>
{
private object _value;
private KeyTimeType _type;
#region Static Create Methods
/// <summary>
/// Creates a KeyTime that represents a Percent value.
/// </summary>
/// <param name="percent">
/// The percent value provided as a double value between 0.0 and 1.0.
/// </param>
public static KeyTime FromPercent(double percent)
{
if (percent < 0.0 || percent > 1.0)
{
throw new ArgumentOutOfRangeException("percent", SR.Get(SRID.Animation_KeyTime_InvalidPercentValue, percent));
}
KeyTime keyTime = new KeyTime();
keyTime._value = percent;
keyTime._type = KeyTimeType.Percent;
return keyTime;
}
/// <summary>
///
/// </summary>
/// <param name="timeSpan"></param>
public static KeyTime FromTimeSpan(TimeSpan timeSpan)
{
if (timeSpan < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException("timeSpan", SR.Get(SRID.Animation_KeyTime_LessThanZero, timeSpan));
}
KeyTime keyTime = new KeyTime();
keyTime._value = timeSpan;
keyTime._type = KeyTimeType.TimeSpan;
return keyTime;
}
/// <summary>
///
/// </summary>
/// <value></value>
public static KeyTime Uniform
{
get
{
KeyTime keyTime = new KeyTime();
keyTime._type = KeyTimeType.Uniform;
return keyTime;
}
}
/// <summary>
///
/// </summary>
/// <value></value>
public static KeyTime Paced
{
get
{
KeyTime keyTime = new KeyTime();
keyTime._type = KeyTimeType.Paced;
return keyTime;
}
}
#endregion
#region Operators
/// <summary>
/// Returns true if two KeyTimes are equal.
/// </summary>
public static bool Equals(KeyTime keyTime1, KeyTime keyTime2)
{
if (keyTime1._type == keyTime2._type)
{
switch (keyTime1._type)
{
case KeyTimeType.Uniform:
break;
case KeyTimeType.Paced:
break;
case KeyTimeType.Percent:
if ((double)keyTime1._value != (double)keyTime2._value)
{
return false;
}
break;
case KeyTimeType.TimeSpan:
if ((TimeSpan)keyTime1._value != (TimeSpan)keyTime2._value)
{
return false;
}
break;
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Returns true if two KeyTimes are equal.
/// </summary>
public static bool operator ==(KeyTime keyTime1, KeyTime keyTime2)
{
return KeyTime.Equals(keyTime1, keyTime2);
}
/// <summary>
/// Returns true if two KeyTimes are not equal.
/// </summary>
public static bool operator !=(KeyTime keyTime1, KeyTime keyTime2)
{
return !KeyTime.Equals(keyTime1, keyTime2);
}
#endregion
#region IEquatable<KeyTime>
/// <summary>
/// Returns true if two KeyTimes are equal.
/// </summary>
public bool Equals(KeyTime value)
{
return KeyTime.Equals(this, value);
}
#endregion
#region Object Overrides
/// <summary>
/// Implementation of <see cref="System.Object.Equals(object)">Object.Equals</see>.
/// </summary>
public override bool Equals(object value)
{
if ( value == null
|| !(value is KeyTime))
{
return false;
}
return this == (KeyTime)value;
}
/// <summary>
/// Implementation of <see cref="System.Object.GetHashCode">Object.GetHashCode</see>.
/// </summary>
public override int GetHashCode()
{
// If we don't have a value (uniform, or paced) then use the type
// to determine the hash code
if (_value != null)
{
return _value.GetHashCode();
}
else
{
return _type.GetHashCode();
}
}
/// <summary>
/// Generates a string representing this KeyTime.
/// </summary>
/// <returns>The generated string.</returns>
public override string ToString()
{
KeyTimeConverter converter = new KeyTimeConverter();
return converter.ConvertToString(this);
}
#endregion
#region Implicit Converters
/// <summary>
/// Implicitly creates a KeyTime value from a Time value.
/// </summary>
/// <param name="timeSpan">The Time value.</param>
/// <returns>A new KeyTime.</returns>
public static implicit operator KeyTime(TimeSpan timeSpan)
{
return KeyTime.FromTimeSpan(timeSpan);
}
#endregion
#region Public Properties
/// <summary>
/// The Time value for this KeyTime.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// Thrown if the type of this KeyTime isn't KeyTimeType.TimeSpan.
/// </exception>
public TimeSpan TimeSpan
{
get
{
if (_type == KeyTimeType.TimeSpan)
{
return (TimeSpan)_value;
}
else
{
#pragma warning suppress 56503 // Suppress presharp warning: Follows a pattern similar to Nullable.
throw new InvalidOperationException();
}
}
}
/// <summary>
/// The percent value for this KeyTime.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// Thrown if the type of this KeyTime isn't KeyTimeType.Percent.
/// </exception>
public double Percent
{
get
{
if (_type == KeyTimeType.Percent)
{
return (double)_value;
}
else
{
#pragma warning suppress 56503 // Suppress presharp warning: Follows a pattern similar to Nullable.
throw new InvalidOperationException();
}
}
}
/// <summary>
/// The type of this KeyTime.
/// </summary>
public KeyTimeType Type
{
get
{
return _type;
}
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Text;
using System.Threading;
using Internal.Runtime.Augments;
using Internal.Metadata.NativeFormat;
using Internal.Reflection.Execution;
namespace Internal.Runtime.TypeLoader
{
public enum ModuleType
{
Eager,
ReadyToRun,
Ecma
}
/// <summary>
/// This class represents basic information about a native binary module including its
/// metadata.
/// </summary>
public unsafe class ModuleInfo
{
/// <summary>
/// Module handle is the TypeManager associated with this module.
/// </summary>
public TypeManagerHandle Handle { get; private set; }
/// <summary>
/// A reference to the dynamic module is part of the EEType for dynamically allocated types.
/// </summary>
internal DynamicModule* DynamicModulePtr { get; private set; }
public IntPtr DynamicModulePtrAsIntPtr => new IntPtr(DynamicModulePtr);
/// <summary>
/// What sort of module is this? (Eager, ReadyToRun)?
/// </summary>
internal ModuleType ModuleType { get; private set; }
/// <summary>
/// Initialize module info and construct per-module metadata reader.
/// </summary>
/// <param name="moduleHandle">Handle (address) of module to initialize</param>
internal ModuleInfo(TypeManagerHandle moduleHandle, ModuleType moduleType)
{
Handle = moduleHandle;
ModuleType = moduleType;
DynamicModule* dynamicModulePtr = (DynamicModule*)MemoryHelpers.AllocateMemory(sizeof(DynamicModule));
dynamicModulePtr->CbSize = DynamicModule.DynamicModuleSize;
Debug.Assert(sizeof(DynamicModule) >= dynamicModulePtr->CbSize);
if ((moduleType == ModuleType.ReadyToRun) || (moduleType == ModuleType.Ecma))
{
// Dynamic type load modules utilize dynamic type resolution
dynamicModulePtr->DynamicTypeSlotDispatchResolve = Intrinsics.AddrOf(
(Func<IntPtr, IntPtr, ushort, IntPtr>)ResolveTypeSlotDispatch);
}
else
{
Debug.Assert(moduleType == ModuleType.Eager);
// Pre-generated modules do not
dynamicModulePtr->DynamicTypeSlotDispatchResolve = IntPtr.Zero;
}
dynamicModulePtr->GetRuntimeException = Intrinsics.AddrOf(
(Func<ExceptionIDs, Exception>)RuntimeExceptionHelpers.GetRuntimeException);
DynamicModulePtr = dynamicModulePtr;
}
internal unsafe static IntPtr ResolveTypeSlotDispatch(IntPtr targetTypeAsIntPtr, IntPtr interfaceTypeAsIntPtr, ushort slot)
{
IntPtr methodAddress;
if (!TypeLoaderEnvironment.Instance.TryResolveTypeSlotDispatch(targetTypeAsIntPtr, interfaceTypeAsIntPtr, slot, out methodAddress))
{
throw new BadImageFormatException();
}
return methodAddress;
}
}
public class NativeFormatModuleInfo : ModuleInfo
{
/// <summary>
/// Initialize module info and construct per-module metadata reader.
/// </summary>
/// <param name="moduleHandle">Handle (address) of module to initialize</param>
internal NativeFormatModuleInfo(TypeManagerHandle moduleHandle, ModuleType moduleType, IntPtr pBlob, int cbBlob) : base (moduleHandle, moduleType)
{
MetadataReader = new MetadataReader((IntPtr)pBlob, (int)cbBlob);
}
/// <summary>
/// Module metadata reader for NativeFormat metadata
/// </summary>
public MetadataReader MetadataReader { get; private set; }
internal unsafe bool TryFindBlob(ReflectionMapBlob blobId, out byte* pBlob, out uint cbBlob)
{
pBlob = null;
cbBlob = 0;
fixed (byte** ppBlob = &pBlob)
{
fixed (uint* pcbBlob = &cbBlob)
{
return RuntimeAugments.FindBlob(Handle, (int)blobId, new IntPtr(ppBlob), new IntPtr(pcbBlob));
}
}
}
public unsafe bool TryFindBlob(int blobId, out byte* pBlob, out uint cbBlob)
{
pBlob = null;
cbBlob = 0;
fixed (byte** ppBlob = &pBlob)
{
fixed (uint* pcbBlob = &cbBlob)
{
return RuntimeAugments.FindBlob(Handle, (int)blobId, new IntPtr(ppBlob), new IntPtr(pcbBlob));
}
}
}
}
/// <summary>
/// This class represents a linear module list and a dictionary mapping module handles
/// to its indices. When a new module is registered, a new instance of this class gets
/// constructed and atomically updates the _loadedModuleMap so that at any point in time
/// all threads see the map as consistent.
/// </summary>
internal sealed class ModuleMap
{
/// <summary>
/// Array of loaded binary modules.
/// </summary>
public readonly ModuleInfo[] Modules;
/// <summary>
/// Map of module handles to indices within the Modules array.
/// </summary>
public readonly LowLevelDictionary<TypeManagerHandle, int> HandleToModuleIndex;
internal ModuleMap(ModuleInfo[] modules)
{
Modules = modules;
HandleToModuleIndex = new LowLevelDictionary<TypeManagerHandle, int>();
for (int moduleIndex = 0; moduleIndex < Modules.Length; moduleIndex++)
{
// Ecma modules don't go in the reverse lookup hash because they share a module index with the system module
if (Modules[moduleIndex].ModuleType != ModuleType.Ecma)
HandleToModuleIndex.Add(Modules[moduleIndex].Handle, moduleIndex);
}
}
}
/// <summary>
/// Helper class that can construct an enumerator for the module info map, possibly adjusting
/// the module order so that a given explicitly specified module goes first - this is used
/// as optimization in cases where a certain module is most likely to contain some metadata.
/// </summary>
public struct ModuleInfoEnumerable
{
/// <summary>
/// Module map to enumerate
/// </summary>
private readonly ModuleMap _moduleMap;
/// <summary>
/// Module handle that should be enumerated first, default(IntPtr) when not used.
/// </summary>
private readonly TypeManagerHandle _preferredModuleHandle;
/// <summary>
/// Store module map and preferred module to pass to the enumerator upon construction.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal ModuleInfoEnumerable(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleMap = moduleMap;
_preferredModuleHandle = preferredModuleHandle;
}
/// <summary>
/// Construct the actual module info enumerator.
/// </summary>
public ModuleInfoEnumerator GetEnumerator()
{
return new ModuleInfoEnumerator(_moduleMap, _preferredModuleHandle);
}
}
/// <summary>
/// This enumerator iterates the module map, possibly adjusting the order to make a given
/// module go first in the enumeration.
/// </summary>
public struct ModuleInfoEnumerator
{
/// <summary>
/// Array of modules to enumerate.
/// </summary>
private readonly ModuleInfo[] _modules;
/// <summary>
/// Preferred module index in the array, -1 when none (in such case the array is enumerated
/// in its natural order).
/// </summary>
private int _preferredIndex;
/// <summary>
/// Enumeration step index initially set to -1 (so that the first MoveNext increments it to 0).
/// </summary>
private int _iterationIndex;
/// <summary>
/// Current _modules element that should be returned by Current (updated in MoveNext).
/// </summary>
private ModuleInfo _currentModule;
/// <summary>
/// Initialize the module enumerator state machine and locate the preferred module index.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal ModuleInfoEnumerator(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_modules = moduleMap.Modules;
_preferredIndex = -1;
_iterationIndex = -1;
_currentModule = null;
if (!preferredModuleHandle.IsNull &&
!moduleMap.HandleToModuleIndex.TryGetValue(preferredModuleHandle, out _preferredIndex))
{
Environment.FailFast("Invalid module requested in enumeration: " + preferredModuleHandle.LowLevelToString());
}
}
/// <summary>
/// Move the enumerator state machine to the next element in the module map.
/// </summary>
/// <returns>true when [another] module is available, false when the enumeration is finished</returns>
public bool MoveNext()
{
if (_iterationIndex + 1 >= _modules.Length)
{
_currentModule = null;
return false;
}
_iterationIndex++;
int moduleIndex = _iterationIndex;
if (moduleIndex <= _preferredIndex)
{
// Transform the index so that the _preferredIndex is returned in first iteration
moduleIndex = (moduleIndex == 0 ? _preferredIndex : moduleIndex - 1);
}
_currentModule = _modules[moduleIndex];
return true;
}
/// <summary>
/// Look up the "current" module corresponding to the previous call to MoveNext.
/// </summary>
public ModuleInfo Current
{
get
{
if (_currentModule == null)
{
Environment.FailFast("Current module queried in wrong enumerator state");
}
return _currentModule;
}
}
}
/// <summary>
/// Helper class that can construct an enumerator for the module info map, possibly adjusting
/// the module order so that a given explicitly specified module goes first - this is used
/// as optimization in cases where a certain module is most likely to contain some metadata.
/// </summary>
public struct NativeFormatModuleInfoEnumerable
{
/// <summary>
/// Module map to enumerate
/// </summary>
private readonly ModuleMap _moduleMap;
/// <summary>
/// Module handle that should be enumerated first, default(IntPtr) when not used.
/// </summary>
private readonly TypeManagerHandle _preferredModuleHandle;
/// <summary>
/// Store module map and preferred module to pass to the enumerator upon construction.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal NativeFormatModuleInfoEnumerable(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleMap = moduleMap;
_preferredModuleHandle = preferredModuleHandle;
}
/// <summary>
/// Construct the actual module info enumerator.
/// </summary>
public NativeFormatModuleInfoEnumerator GetEnumerator()
{
return new NativeFormatModuleInfoEnumerator(_moduleMap, _preferredModuleHandle);
}
}
/// <summary>
/// This enumerator iterates the module map, possibly adjusting the order to make a given
/// module go first in the enumeration.
/// </summary>
public struct NativeFormatModuleInfoEnumerator
{
/// <summary>
/// Array of modules to enumerate.
/// </summary>
private readonly ModuleInfo[] _modules;
/// <summary>
/// Preferred module index in the array, -1 when none (in such case the array is enumerated
/// in its natural order).
/// </summary>
private int _preferredIndex;
/// <summary>
/// Enumeration step index initially set to -1 (so that the first MoveNext increments it to 0).
/// </summary>
private int _iterationIndex;
/// <summary>
/// Current _modules element that should be returned by Current (updated in MoveNext).
/// </summary>
private NativeFormatModuleInfo _currentModule;
/// <summary>
/// Initialize the module enumerator state machine and locate the preferred module index.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal NativeFormatModuleInfoEnumerator(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_modules = moduleMap.Modules;
_preferredIndex = -1;
_iterationIndex = -1;
_currentModule = null;
if (!preferredModuleHandle.IsNull &&
!moduleMap.HandleToModuleIndex.TryGetValue(preferredModuleHandle, out _preferredIndex))
{
Environment.FailFast("Invalid module requested in enumeration: " + preferredModuleHandle.LowLevelToString());
}
}
/// <summary>
/// Move the enumerator state machine to the next element in the module map.
/// </summary>
/// <returns>true when [another] module is available, false when the enumeration is finished</returns>
public bool MoveNext()
{
do
{
if (_iterationIndex + 1 >= _modules.Length)
{
_currentModule = null;
return false;
}
_iterationIndex++;
int moduleIndex = _iterationIndex;
if (moduleIndex <= _preferredIndex)
{
// Transform the index so that the _preferredIndex is returned in first iteration
moduleIndex = (moduleIndex == 0 ? _preferredIndex : moduleIndex - 1);
}
_currentModule = _modules[moduleIndex] as NativeFormatModuleInfo;
} while (_currentModule == null);
return true;
}
/// <summary>
/// Look up the "current" module corresponding to the previous call to MoveNext.
/// </summary>
public NativeFormatModuleInfo Current
{
get
{
if (_currentModule == null)
{
Environment.FailFast("Current module queried in wrong enumerator state");
}
return _currentModule;
}
}
}
/// <summary>
/// Helper class that can construct an enumerator for the module handle map, possibly adjusting
/// the module order so that a given explicitly specified module goes first - this is used
/// as optimization in cases where a certain module is most likely to contain some metadata.
/// </summary>
public struct ModuleHandleEnumerable
{
/// <summary>
/// Module map to enumerate
/// </summary>
private readonly ModuleMap _moduleMap;
/// <summary>
/// Module handle that should be enumerated first, default(IntPtr) when not used.
/// </summary>
private readonly TypeManagerHandle _preferredModuleHandle;
/// <summary>
/// Store module map and preferred module to pass to the enumerator upon construction.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal ModuleHandleEnumerable(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleMap = moduleMap;
_preferredModuleHandle = preferredModuleHandle;
}
/// <summary>
/// Create the actual module handle enumerator.
/// </summary>
public ModuleHandleEnumerator GetEnumerator()
{
return new ModuleHandleEnumerator(_moduleMap, _preferredModuleHandle);
}
}
/// <summary>
/// Enumerator for module handles, optionally overriding module order with a given preferred
/// module to be enumerated first.
/// </summary>
public struct ModuleHandleEnumerator
{
/// <summary>
/// The underlying ModuleInfoEnumerator handles enumeration internals
/// </summary>
private ModuleInfoEnumerator _moduleInfoEnumerator;
/// <summary>
/// Construct the underlying module info enumerator used to iterate the module map
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal ModuleHandleEnumerator(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleInfoEnumerator = new ModuleInfoEnumerator(moduleMap, preferredModuleHandle);
}
/// <summary>
/// Move to next element in the module map. Return true when an element is available,
/// false when the enumeration is finished.
/// </summary>
public bool MoveNext()
{
bool result;
do
{
result = _moduleInfoEnumerator.MoveNext();
// Ecma module shouldn't be reported as they should not be enumerated by ModuleHandle (as its always the System module)
if (!result || (_moduleInfoEnumerator.Current.ModuleType != ModuleType.Ecma))
{
break;
}
} while(true);
return result;
}
/// <summary>
/// Return current module handle.
/// </summary>
public TypeManagerHandle Current
{
get { return _moduleInfoEnumerator.Current.Handle; }
}
}
/// <summary>
/// Helper class that can construct an enumerator for module metadata readers, possibly adjusting
/// the module order so that a given explicitly specified module goes first - this is used
/// as optimization in cases where a certain module is most likely to contain some metadata.
/// </summary>
public struct MetadataReaderEnumerable
{
/// <summary>
/// Module map to enumerate
/// </summary>
private readonly ModuleMap _moduleMap;
/// <summary>
/// Module handle that should be enumerated first, default(IntPtr) when not used.
/// </summary>
private readonly TypeManagerHandle _preferredModuleHandle;
/// <summary>
/// Store module map and preferred module to pass to the enumerator upon construction.
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal MetadataReaderEnumerable(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleMap = moduleMap;
_preferredModuleHandle = preferredModuleHandle;
}
/// <summary>
/// Create the actual module handle enumerator.
/// </summary>
public MetadataReaderEnumerator GetEnumerator()
{
return new MetadataReaderEnumerator(_moduleMap, _preferredModuleHandle);
}
}
/// <summary>
/// Enumerator for metadata readers, optionally overriding module order with a given preferred
/// module to be enumerated first.
/// </summary>
public struct MetadataReaderEnumerator
{
/// <summary>
/// The underlying ModuleInfoEnumerator handles enumeration internals
/// </summary>
private NativeFormatModuleInfoEnumerator _moduleInfoEnumerator;
/// <summary>
/// Construct the underlying module info enumerator used to iterate the module map
/// </summary>
/// <param name="moduleMap">Module map to enumerate</param>
/// <param name="preferredModuleHandle">Optional module handle to enumerate first</param>
internal MetadataReaderEnumerator(ModuleMap moduleMap, TypeManagerHandle preferredModuleHandle)
{
_moduleInfoEnumerator = new NativeFormatModuleInfoEnumerator(moduleMap, preferredModuleHandle);
}
/// <summary>
/// Move to next element in the module map. Return true when an element is available,
/// false when the enumeration is finished.
/// </summary>
public bool MoveNext()
{
return _moduleInfoEnumerator.MoveNext();
}
/// <summary>
/// Return current metadata reader.
/// </summary>
public MetadataReader Current
{
get { return _moduleInfoEnumerator.Current.MetadataReader; }
}
}
/// <summary>
/// Utilities for manipulating module list and metadata readers.
/// </summary>
public sealed class ModuleList
{
/// <summary>
/// Map of module addresses to module info. Every time a new module is loaded,
/// the reference gets atomically updated to a newly copied instance of the dictionary
/// to that consumers of this dictionary can look at the reference and enumerate / process it without locking, fear that the contents of the dictionary change
/// under its hands.
/// </summary>
private volatile ModuleMap _loadedModuleMap;
internal ModuleMap GetLoadedModuleMapInternal() { return _loadedModuleMap; }
/// <summary>
/// List of callbacks to execute when a module gets registered.
/// </summary>
private Action<ModuleInfo> _moduleRegistrationCallbacks;
/// <summary>
/// Lock used for serializing module registrations.
/// </summary>
private Lock _moduleRegistrationLock;
/// <summary>
/// Base Module (module that contains System.Object)
/// </summary>
private ModuleInfo _systemModule;
/// <summary>
/// Register initially (eagerly) loaded modules.
/// </summary>
internal ModuleList()
{
_loadedModuleMap = new ModuleMap(new ModuleInfo[0]);
_moduleRegistrationCallbacks = default(Action<ModuleInfo>);
_moduleRegistrationLock = new Lock();
RegisterNewModules(ModuleType.Eager);
TypeManagerHandle systemObjectModule = RuntimeAugments.GetModuleFromTypeHandle(RuntimeAugments.RuntimeTypeHandleOf<object>());
foreach (ModuleInfo m in _loadedModuleMap.Modules)
{
if (m.Handle == systemObjectModule)
{
_systemModule = m;
break;
}
}
}
/// <summary>
/// Module list is a process-wide singleton that physically lives in the TypeLoaderEnvironment instance.
/// </summary>
public static ModuleList Instance
{
get { return TypeLoaderEnvironment.Instance.ModuleList; }
}
/// <summary>
/// Register a new callback that gets called whenever a new module gets registered.
/// The module registration happens under a global lock so that the module registration
/// callbacks are never called concurrently.
/// </summary>
/// <param name="moduleRegistrationCallback">Method to call whenever a new module is registered</param>
public static void AddModuleRegistrationCallback(Action<ModuleInfo> newModuleRegistrationCallback)
{
// Accumulate callbacks to be notified upon module registration
Instance._moduleRegistrationCallbacks += newModuleRegistrationCallback;
// Invoke the new callback for all modules that have already been registered
foreach (ModuleInfo moduleInfo in EnumerateModules())
{
newModuleRegistrationCallback(moduleInfo);
}
}
/// <summary>
/// This helper method is called at the end of StartupCodeTrigger during main app build
/// to refresh the module list after all modules have been registered in StartupCodeHelpers.
/// </summary>
#if PROJECTN
public static void RegisterEagerModules()
{
TypeLoaderEnvironment.Instance.ModuleList.RegisterNewModules(ModuleType.Eager);
}
#endif
/// <summary>
/// Register all modules which were added (Registered) to the runtime and are not already registered with the TypeLoader.
/// </summary>
/// <param name="moduleType">Type to assign to all new modules.</param>
public void RegisterNewModules(ModuleType moduleType)
{
// prevent multiple threads from registering modules concurrently
using (LockHolder.Hold(_moduleRegistrationLock))
{
// Fetch modules that have already been registered with the runtime
int loadedModuleCount = RuntimeAugments.GetLoadedModules(null);
TypeManagerHandle[] loadedModuleHandles = new TypeManagerHandle[loadedModuleCount];
int loadedModuleCountUpdated = RuntimeAugments.GetLoadedModules(loadedModuleHandles);
Debug.Assert(loadedModuleCount == loadedModuleCountUpdated);
LowLevelList<TypeManagerHandle> newModuleHandles = new LowLevelList<TypeManagerHandle>(loadedModuleHandles.Length);
foreach (TypeManagerHandle moduleHandle in loadedModuleHandles)
{
// Skip already registered modules.
int oldModuleIndex;
if (_loadedModuleMap.HandleToModuleIndex.TryGetValue(moduleHandle, out oldModuleIndex))
{
continue;
}
newModuleHandles.Add(moduleHandle);
}
// Copy existing modules to new dictionary
int oldModuleCount = _loadedModuleMap.Modules.Length;
ModuleInfo[] updatedModules = new ModuleInfo[oldModuleCount + newModuleHandles.Count];
if (oldModuleCount > 0)
{
Array.Copy(_loadedModuleMap.Modules, 0, updatedModules, 0, oldModuleCount);
}
for (int newModuleIndex = 0; newModuleIndex < newModuleHandles.Count; newModuleIndex++)
{
ModuleInfo newModuleInfo;
unsafe
{
byte* pBlob;
uint cbBlob;
if (RuntimeAugments.FindBlob(newModuleHandles[newModuleIndex], (int)ReflectionMapBlob.EmbeddedMetadata, new IntPtr(&pBlob), new IntPtr(&cbBlob)))
{
newModuleInfo = new NativeFormatModuleInfo(newModuleHandles[newModuleIndex], moduleType, (IntPtr)pBlob, (int)cbBlob);
}
else
{
newModuleInfo = new ModuleInfo(newModuleHandles[newModuleIndex], moduleType);
}
}
updatedModules[oldModuleCount + newModuleIndex] = newModuleInfo;
if (_moduleRegistrationCallbacks != null)
{
_moduleRegistrationCallbacks(newModuleInfo);
}
}
// Atomically update the module map
_loadedModuleMap = new ModuleMap(updatedModules);
}
}
public void RegisterModule(ModuleInfo newModuleInfo)
{
// prevent multiple threads from registering modules concurrently
using (LockHolder.Hold(_moduleRegistrationLock))
{
// Copy existing modules to new dictionary
int oldModuleCount = _loadedModuleMap.Modules.Length;
ModuleInfo[] updatedModules = new ModuleInfo[oldModuleCount + 1];
if (oldModuleCount > 0)
{
Array.Copy(_loadedModuleMap.Modules, 0, updatedModules, 0, oldModuleCount);
}
updatedModules[oldModuleCount] = newModuleInfo;
if (_moduleRegistrationCallbacks != null)
{
_moduleRegistrationCallbacks(newModuleInfo);
}
// Atomically update the module map
_loadedModuleMap = new ModuleMap(updatedModules);
}
}
/// <summary>
/// Locate module info for a given module. Fail if not found or before the module registry
/// gets initialized. Must only be called for modules described as native format (not the mrt module, or an ECMA module)
/// </summary>
/// <param name="moduleHandle">Handle of module to look up</param>
public NativeFormatModuleInfo GetModuleInfoByHandle(TypeManagerHandle moduleHandle)
{
ModuleMap moduleMap = _loadedModuleMap;
return (NativeFormatModuleInfo)moduleMap.Modules[moduleMap.HandleToModuleIndex[moduleHandle]];
}
/// <summary>
/// Try to Locate module info for a given module. Returns false when not found.
/// gets initialized.
/// </summary>
/// <param name="moduleHandle">Handle of module to look up</param>
public bool TryGetModuleInfoByHandle(TypeManagerHandle moduleHandle, out ModuleInfo moduleInfo)
{
ModuleMap moduleMap = _loadedModuleMap;
int moduleIndex;
if (moduleMap.HandleToModuleIndex.TryGetValue(moduleHandle, out moduleIndex))
{
moduleInfo = moduleMap.Modules[moduleIndex];
return true;
}
moduleInfo = null;
return false;
}
/// <summary>
/// Given module handle, locate the metadata reader. Return null when not found.
/// </summary>
/// <param name="moduleHandle">Handle of module to look up</param>
/// <returns>Reader for the embedded metadata blob in the module, null when not found</returns>
public MetadataReader GetMetadataReaderForModule(TypeManagerHandle moduleHandle)
{
ModuleMap moduleMap = _loadedModuleMap;
int moduleIndex;
if (moduleMap.HandleToModuleIndex.TryGetValue(moduleHandle, out moduleIndex))
{
NativeFormatModuleInfo moduleInfo = moduleMap.Modules[moduleIndex] as NativeFormatModuleInfo;
if (moduleInfo != null)
return moduleInfo.MetadataReader;
else
return null;
}
return null;
}
/// <summary>
/// Given dynamic module handle, locate the moduleinfo
/// </summary>
/// <param name="moduleHandle">Handle of module to look up</param>
/// <returns>fails if not found</returns>
public unsafe ModuleInfo GetModuleInfoForDynamicModule(IntPtr dynamicModuleHandle)
{
foreach (ModuleInfo moduleInfo in _loadedModuleMap.Modules)
{
if (new IntPtr(moduleInfo.DynamicModulePtr) == dynamicModuleHandle)
return moduleInfo;
}
// We should never have a dynamic module that is not associated with a module (where does it come from?!)
Debug.Assert(false);
return null;
}
/// <summary>
/// Locate the containing module for a given metadata reader. Assert when not found.
/// </summary>
/// <param name="reader">Metadata reader to look up</param>
/// <returns>Module handle of the module containing the given reader</returns>
public NativeFormatModuleInfo GetModuleInfoForMetadataReader(MetadataReader reader)
{
foreach (ModuleInfo moduleInfo in _loadedModuleMap.Modules)
{
NativeFormatModuleInfo nativeFormatModuleInfo = moduleInfo as NativeFormatModuleInfo;
if (nativeFormatModuleInfo != null && nativeFormatModuleInfo.MetadataReader == reader)
{
return nativeFormatModuleInfo;
}
}
// We should never have a reader that is not associated with a module (where does it come from?!)
Debug.Assert(false);
return null;
}
/// <summary>
/// Locate the containing module for a given metadata reader. Assert when not found.
/// </summary>
/// <param name="reader">Metadata reader to look up</param>
/// <returns>Module handle of the module containing the given reader</returns>
public TypeManagerHandle GetModuleForMetadataReader(MetadataReader reader)
{
foreach (ModuleInfo moduleInfo in _loadedModuleMap.Modules)
{
NativeFormatModuleInfo nativeFormatModuleInfo = moduleInfo as NativeFormatModuleInfo;
if (nativeFormatModuleInfo != null && nativeFormatModuleInfo.MetadataReader == reader)
{
return moduleInfo.Handle;
}
}
// We should never have a reader that is not associated with a module (where does it come from?!)
Debug.Assert(false);
return default(TypeManagerHandle);
}
/// <summary>
/// Base Module (module that contains System.Object)
/// </summary>
public ModuleInfo SystemModule
{
get
{
return _systemModule;
}
}
/// <summary>
/// Enumerate modules.
/// </summary>
public static NativeFormatModuleInfoEnumerable EnumerateModules()
{
return new NativeFormatModuleInfoEnumerable(Instance._loadedModuleMap, default(TypeManagerHandle));
}
/// <summary>
/// Enumerate modules. Specify a module that should be enumerated first
/// - this is used as an optimization in cases when a certain binary module is more probable
/// to contain a certain information.
/// </summary>
/// <param name="preferredModule">Handle to the module which should be enumerated first</param>
public static NativeFormatModuleInfoEnumerable EnumerateModules(TypeManagerHandle preferredModule)
{
return new NativeFormatModuleInfoEnumerable(Instance._loadedModuleMap, preferredModule);
}
/// <summary>
/// Enumerate metadata readers.
/// </summary>
public static MetadataReaderEnumerable EnumerateMetadataReaders()
{
return new MetadataReaderEnumerable(Instance._loadedModuleMap, default(TypeManagerHandle));
}
/// <summary>
/// Enumerate metadata readers. Specify a module that should be enumerated first
/// - this is used as an optimization in cases when a certain binary module is more probable
/// to contain a certain information.
/// </summary>
/// <param name="preferredModule">Handle to the module which should be enumerated first</param>
public static MetadataReaderEnumerable EnumerateMetadataReaders(TypeManagerHandle preferredModule)
{
return new MetadataReaderEnumerable(Instance._loadedModuleMap, preferredModule);
}
/// <summary>
/// Enumerate module handles (simplified version for code that only needs the module addresses).
/// </summary>
public static ModuleHandleEnumerable Enumerate()
{
return new ModuleHandleEnumerable(Instance._loadedModuleMap, default(TypeManagerHandle));
}
/// <summary>
/// Enumerate module handles (simplified version for code that only needs the module addresses).
/// Specify a module that should be enumerated first
/// - this is used as an optimization in cases when a certain binary module is more probable
/// to contain a certain information.
/// </summary>
/// <param name="preferredModule">Handle to the module which should be enumerated first</param>
public static ModuleHandleEnumerable Enumerate(TypeManagerHandle preferredModule)
{
return new ModuleHandleEnumerable(Instance._loadedModuleMap, preferredModule);
}
}
public static partial class RuntimeSignatureHelper
{
public static ModuleInfo GetModuleInfo(this Internal.Runtime.CompilerServices.RuntimeSignature methodSignature)
{
if (methodSignature.IsNativeLayoutSignature)
{
return ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSignature.ModuleHandle));
}
else
{
ModuleInfo moduleInfo;
if (!ModuleList.Instance.TryGetModuleInfoByHandle(new TypeManagerHandle(methodSignature.ModuleHandle), out moduleInfo))
{
moduleInfo = ModuleList.Instance.GetModuleInfoForDynamicModule(methodSignature.ModuleHandle);
}
return moduleInfo;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ConversationThreadPostsCollectionRequest.
/// </summary>
public partial class ConversationThreadPostsCollectionRequest : BaseRequest, IConversationThreadPostsCollectionRequest
{
/// <summary>
/// Constructs a new ConversationThreadPostsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ConversationThreadPostsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Post to the collection via POST.
/// </summary>
/// <param name="post">The Post to add.</param>
/// <returns>The created Post.</returns>
public System.Threading.Tasks.Task<Post> AddAsync(Post post)
{
return this.AddAsync(post, CancellationToken.None);
}
/// <summary>
/// Adds the specified Post to the collection via POST.
/// </summary>
/// <param name="post">The Post to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Post.</returns>
public System.Threading.Tasks.Task<Post> AddAsync(Post post, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Post>(post, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IConversationThreadPostsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IConversationThreadPostsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<ConversationThreadPostsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Expand(Expression<Func<Post, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Select(Expression<Func<Post, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadPostsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using EnvDTE;
using Microsoft.Build.Evaluation;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using VsWebSite;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using Project = EnvDTE.Project;
using ProjectItem = EnvDTE.ProjectItem;
namespace NuGet.VisualStudio
{
public static class ProjectExtensions
{
private const string WebConfig = "web.config";
private const string AppConfig = "app.config";
private const string BinFolder = "Bin";
private static readonly Dictionary<string, string> _knownNestedFiles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "web.debug.config", "web.config" },
{ "web.release.config", "web.config" }
};
private static readonly HashSet<string> _supportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
VsConstants.WebSiteProjectTypeGuid,
VsConstants.CsharpProjectTypeGuid,
VsConstants.VbProjectTypeGuid,
VsConstants.JsProjectTypeGuid,
VsConstants.FsharpProjectTypeGuid,
VsConstants.NemerleProjectTypeGuid,
VsConstants.WixProjectTypeGuid };
private static readonly HashSet<string> _unsupportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
VsConstants.LightSwitchProjectTypeGuid,
VsConstants.InstallShieldLimitedEditionTypeGuid
};
private static readonly IEnumerable<string> _fileKinds = new[] { VsConstants.VsProjectItemKindPhysicalFile, VsConstants.VsProjectItemKindSolutionItem };
private static readonly IEnumerable<string> _folderKinds = new[] { VsConstants.VsProjectItemKindPhysicalFolder };
// List of project types that cannot have references added to them
private static readonly string[] _unsupportedProjectTypesForAddingReferences = new[] { VsConstants.WixProjectTypeGuid };
// List of project types that cannot have binding redirects added
private static readonly string[] _unsupportedProjectTypesForBindingRedirects = new[] { VsConstants.WixProjectTypeGuid, VsConstants.JsProjectTypeGuid, VsConstants.NemerleProjectTypeGuid };
private static readonly char[] PathSeparatorChars = new[] { Path.DirectorySeparatorChar };
// Get the ProjectItems for a folder path
public static ProjectItems GetProjectItems(this Project project, string folderPath, bool createIfNotExists = false)
{
if (String.IsNullOrEmpty(folderPath))
{
return project.ProjectItems;
}
// Traverse the path to get at the directory
string[] pathParts = folderPath.Split(PathSeparatorChars, StringSplitOptions.RemoveEmptyEntries);
// 'cursor' can contain a reference to either a Project instance or ProjectItem instance.
// Both types have the ProjectItems property that we want to access.
dynamic cursor = project;
string fullPath = project.GetFullPath();
string folderRelativePath = String.Empty;
foreach (string part in pathParts)
{
fullPath = Path.Combine(fullPath, part);
folderRelativePath = Path.Combine(folderRelativePath, part);
cursor = GetOrCreateFolder(project, cursor, fullPath, folderRelativePath, part, createIfNotExists);
if (cursor == null)
{
return null;
}
}
return cursor.ProjectItems;
}
public static ProjectItem GetProjectItem(this Project project, string path)
{
string folderPath = Path.GetDirectoryName(path);
string itemName = Path.GetFileName(path);
ProjectItems container = GetProjectItems(project, folderPath);
ProjectItem projectItem;
// If we couldn't get the folder, or the child item doesn't exist, return null
if (container == null ||
(!container.TryGetFile(itemName, out projectItem) &&
!container.TryGetFolder(itemName, out projectItem)))
{
return null;
}
return projectItem;
}
/// <summary>
/// Recursively retrieves all supported child projects of a virtual folder.
/// </summary>
/// <param name="project">The root container project</param>
public static IEnumerable<Project> GetSupportedChildProjects(this Project project)
{
if (!project.IsSolutionFolder())
{
yield break;
}
var containerProjects = new Queue<Project>();
containerProjects.Enqueue(project);
while (containerProjects.Any())
{
var containerProject = containerProjects.Dequeue();
foreach (ProjectItem item in containerProject.ProjectItems)
{
var nestedProject = item.SubProject;
if (nestedProject == null)
{
continue;
}
else if (nestedProject.IsSupported())
{
yield return nestedProject;
}
else if (nestedProject.IsSolutionFolder())
{
containerProjects.Enqueue(nestedProject);
}
}
}
}
public static bool DeleteProjectItem(this Project project, string path)
{
ProjectItem projectItem = GetProjectItem(project, path);
if (projectItem == null)
{
return false;
}
projectItem.Delete();
return true;
}
public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem)
{
projectItem = GetProjectItem(projectItems, name, _folderKinds);
return projectItem != null;
}
public static bool TryGetFile(this ProjectItems projectItems, string name, out ProjectItem projectItem)
{
projectItem = GetProjectItem(projectItems, name, _fileKinds);
if (projectItem == null)
{
// Try to get the nested project item
return TryGetFileNestedFile(projectItems, name, out projectItem);
}
return projectItem != null;
}
/// <summary>
/// // If we didn't find the project item at the top level, then we look one more level down.
/// In VS files can have other nested files like foo.aspx and foo.aspx.cs or web.config and web.debug.config.
/// These are actually top level files in the file system but are represented as nested project items in VS.
/// </summary>
private static bool TryGetFileNestedFile(ProjectItems projectItems, string name, out ProjectItem projectItem)
{
string parentFileName;
if (!_knownNestedFiles.TryGetValue(name, out parentFileName))
{
parentFileName = Path.GetFileNameWithoutExtension(name);
}
// If it's not one of the known nested files then we're going to look up prefixes backwards
// i.e. if we're looking for foo.aspx.cs then we look for foo.aspx then foo.aspx.cs as a nested file
ProjectItem parentProjectItem = GetProjectItem(projectItems, parentFileName, _fileKinds);
if (parentProjectItem != null)
{
// Now try to find the nested file
projectItem = GetProjectItem(parentProjectItem.ProjectItems, name, _fileKinds);
}
else
{
projectItem = null;
}
return projectItem != null;
}
public static bool SupportsConfig(this Project project)
{
return !IsClassLibrary(project);
}
private static bool IsClassLibrary(this Project project)
{
if (project.IsWebSite())
{
return false;
}
// Consider class libraries projects that have one project type guid and an output type of project library.
var outputType = project.GetPropertyValue<prjOutputType>("OutputType");
return project.GetProjectTypeGuids().Count() == 1 &&
outputType == prjOutputType.prjOutputTypeLibrary;
}
public static string GetName(this Project project)
{
string name = project.Name;
if (project.IsJavaScriptProject())
{
// The JavaScript project initially returns a "(loading..)" suffix to the project Name.
// Need to get rid of it for the rest of NuGet to work properly.
// TODO: Follow up with the VS team to see if this will be fixed eventually
const string suffix = " (loading...)";
if (name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(0, name.Length - suffix.Length);
}
}
return name;
}
public static bool IsJavaScriptProject(this Project project)
{
return project != null && VsConstants.JsProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase);
}
// TODO: Return null for library projects
public static string GetConfigurationFile(this Project project)
{
return project.IsWebProject() ? WebConfig : AppConfig;
}
private static ProjectItem GetProjectItem(this ProjectItems projectItems, string name, IEnumerable<string> allowedItemKinds)
{
try
{
ProjectItem projectItem = projectItems.Item(name);
if (projectItem != null && allowedItemKinds.Contains(projectItem.Kind, StringComparer.OrdinalIgnoreCase))
{
return projectItem;
}
}
catch
{
}
return null;
}
public static IEnumerable<ProjectItem> GetChildItems(this Project project, string path, string filter, params string[] kinds)
{
ProjectItems projectItems = GetProjectItems(project, path);
if (projectItems == null)
{
return Enumerable.Empty<ProjectItem>();
}
Regex matcher = filter.Equals("*.*", StringComparison.OrdinalIgnoreCase) ? null : GetFilterRegex(filter);
return from ProjectItem p in projectItems
where kinds.Contains(p.Kind) && (matcher == null || matcher.IsMatch(p.Name))
select p;
}
public static string GetFullPath(this Project project)
{
string fullPath = project.GetPropertyValue<string>("FullPath");
if (!String.IsNullOrEmpty(fullPath))
{
// Some Project System implementations (JS metro app) return the project
// file as FullPath. We only need the parent directory
if (File.Exists(fullPath))
{
fullPath = Path.GetDirectoryName(fullPath);
}
}
return fullPath;
}
public static string GetTargetFramework(this Project project)
{
if (project.IsJavaScriptProject())
{
// HACK: The JS Metro project does not have a TargetFrameworkMoniker property set.
// We hard-code the return value so that it behaves as if it had a WinRT target
// framework, i.e. .NETCore, Version=4.5
// Review: What about future versions? Let's not worry about that for now.
return ".NETCore, Version=4.5";
}
return project.GetPropertyValue<string>("TargetFrameworkMoniker");
}
public static T GetPropertyValue<T>(this Project project, string propertyName)
{
try
{
Property property = project.Properties.Item(propertyName);
if (property != null)
{
// REVIEW: Should this cast or convert?
return (T)property.Value;
}
}
catch (ArgumentException)
{
}
return default(T);
}
private static Regex GetFilterRegex(string wildcard)
{
string pattern = String.Join(String.Empty, wildcard.Split('.').Select(GetPattern));
return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
private static string GetPattern(string token)
{
return token == "*" ? @"(.*)" : @"(" + token + ")";
}
// 'parentItem' can be either a Project or ProjectItem
private static ProjectItem GetOrCreateFolder(
Project project,
dynamic parentItem,
string fullPath,
string folderRelativePath,
string folderName,
bool createIfNotExists)
{
if (parentItem == null)
{
return null;
}
ProjectItem subFolder;
ProjectItems projectItems = parentItem.ProjectItems;
if (projectItems.TryGetFolder(folderName, out subFolder))
{
// Get the sub folder
return subFolder;
}
else if (createIfNotExists)
{
// The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that
// does not belong to the project will throw. To work around that, we have to manually include
// it into our project.
if (project.IsJavaScriptProject() && Directory.Exists(fullPath))
{
bool succeeded = IncludeExistingFolderToProject(project, folderRelativePath);
if (succeeded)
{
// IMPORTANT: after including the folder into project, we need to get
// a new ProjectItems snapshot from the parent item. Otheriwse, reusing
// the old snapshot from above won't have access to the added folder.
projectItems = parentItem.ProjectItems;
if (projectItems.TryGetFolder(folderName, out subFolder))
{
// Get the sub folder
return subFolder;
}
}
return null;
}
try
{
return projectItems.AddFromDirectory(fullPath);
}
catch (NotImplementedException)
{
// This is the case for F#'s project system, we can't add from directory so we fall back
// to this impl
return projectItems.AddFolder(folderName);
}
}
return null;
}
private static bool IncludeExistingFolderToProject(Project project, string folderRelativePath)
{
IVsUIHierarchy projectHierarchy = (IVsUIHierarchy)project.ToVsHierarchy();
uint itemId;
int hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out itemId);
if (!ErrorHandler.Succeeded(hr))
{
return false;
}
// Execute command to include the existing folder into project. Must do this on UI thread.
hr = ThreadHelper.Generic.Invoke(() =>
projectHierarchy.ExecCommand(
itemId,
ref VsMenus.guidStandardCommandSet2K,
(int)VSConstants.VSStd2KCmdID.INCLUDEINPROJECT,
0,
IntPtr.Zero,
IntPtr.Zero));
return ErrorHandler.Succeeded(hr);
}
public static bool IsWebProject(this Project project)
{
var types = new HashSet<string>(project.GetProjectTypeGuids(), StringComparer.OrdinalIgnoreCase);
return types.Contains(VsConstants.WebSiteProjectTypeGuid) || types.Contains(VsConstants.WebApplicationProjectTypeGuid);
}
public static bool IsWebSite(this Project project)
{
return project.Kind != null && project.Kind.Equals(VsConstants.WebSiteProjectTypeGuid, StringComparison.OrdinalIgnoreCase);
}
public static bool IsSupported(this Project project)
{
return project.Kind != null && _supportedProjectTypes.Contains(project.Kind);
}
public static bool IsExplicitlyUnsupported(this Project project)
{
return project.Kind == null || _unsupportedProjectTypes.Contains(project.Kind);
}
public static bool IsSolutionFolder(this Project project)
{
return project.Kind != null && project.Kind.Equals(VsConstants.VsProjectItemKindSolutionFolder, StringComparison.OrdinalIgnoreCase);
}
public static bool IsTopLevelSolutionFolder(this Project project)
{
return IsSolutionFolder(project) && project.ParentProjectItem == null;
}
public static bool SupportsReferences(this Project project)
{
return project.Kind != null &&
!_unsupportedProjectTypesForAddingReferences.Contains(project.Kind, StringComparer.OrdinalIgnoreCase);
}
public static bool SupportsBindingRedirects(this Project project)
{
return project.Kind != null &
!_unsupportedProjectTypesForBindingRedirects.Contains(project.Kind, StringComparer.OrdinalIgnoreCase);
}
public static bool IsUnloaded(this Project project)
{
return VsConstants.UnloadedProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase);
}
public static string GetOutputPath(this Project project)
{
// For Websites the output path is the bin folder
string outputPath = project.IsWebSite() ? BinFolder : project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
return Path.Combine(project.GetFullPath(), outputPath);
}
public static IVsHierarchy ToVsHierarchy(this Project project)
{
IVsHierarchy hierarchy;
// Get the vs solution
IVsSolution solution = ServiceLocator.GetInstance<IVsSolution>();
int hr = solution.GetProjectOfUniqueName(project.UniqueName, out hierarchy);
if (hr != VsConstants.S_OK)
{
Marshal.ThrowExceptionForHR(hr);
}
return hierarchy;
}
public static IVsProjectBuildSystem ToVsProjectBuildSystem(this Project project)
{
if (project == null)
{
throw new ArgumentNullException("project");
}
// Convert the project to an IVsHierarchy and see if it implements IVsProjectBuildSystem
return project.ToVsHierarchy() as IVsProjectBuildSystem;
}
public static bool IsCompatible(this Project project, IPackage package)
{
if (package == null)
{
return true;
}
FrameworkName frameworkName = project.GetTargetFrameworkName();
return VersionUtility.IsCompatible(frameworkName, package.GetSupportedFrameworks());
}
public static FrameworkName GetTargetFrameworkName(this Project project)
{
string targetFrameworkMoniker = project.GetTargetFramework();
if (targetFrameworkMoniker != null)
{
return new FrameworkName(targetFrameworkMoniker);
}
return null;
}
public static IEnumerable<string> GetProjectTypeGuids(this Project project)
{
// Get the vs hierarchy as an IVsAggregatableProject to get the project type guids
var hierarchy = project.ToVsHierarchy();
var aggregatableProject = hierarchy as IVsAggregatableProject;
if (aggregatableProject != null)
{
string projectTypeGuids;
int hr = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids);
if (hr != VsConstants.S_OK)
{
Marshal.ThrowExceptionForHR(hr);
}
return projectTypeGuids.Split(';');
}
else if (!String.IsNullOrEmpty(project.Kind))
{
return new[] { project.Kind };
}
else
{
return new string[0];
}
}
internal static IEnumerable<Project> GetReferencedProjects(this Project project)
{
if (project.IsWebSite())
{
return GetWebsiteReferencedProjects(project);
}
var projects = new List<Project>();
References references = project.Object.References;
foreach (Reference reference in references)
{
// Get the referenced project from the reference if any
if (reference.SourceProject != null)
{
projects.Add(reference.SourceProject);
}
}
return projects;
}
internal static HashSet<string> GetAssemblyClosure(this Project project, IDictionary<string, HashSet<string>> visitedProjects)
{
HashSet<string> assemblies;
if (visitedProjects.TryGetValue(project.UniqueName, out assemblies))
{
return assemblies;
}
assemblies = new HashSet<string>(PathComparer.Default);
assemblies.AddRange(GetLocalProjectAssemblies(project));
assemblies.AddRange(project.GetReferencedProjects().SelectMany(p => GetAssemblyClosure(p, visitedProjects)));
visitedProjects.Add(project.UniqueName, assemblies);
return assemblies;
}
private static IEnumerable<Project> GetWebsiteReferencedProjects(Project project)
{
var projects = new List<Project>();
AssemblyReferences references = project.Object.References;
foreach (AssemblyReference reference in references)
{
if (reference.ReferencedProject != null)
{
projects.Add(reference.ReferencedProject);
}
}
return projects;
}
private static HashSet<string> GetLocalProjectAssemblies(Project project)
{
if (project.IsWebSite())
{
return GetWebsiteLocalAssemblies(project);
}
var assemblies = new HashSet<string>(PathComparer.Default);
References references = project.Object.References;
foreach (Reference reference in references)
{
// Get the referenced project from the reference if any
if (reference.SourceProject == null &&
reference.CopyLocal &&
File.Exists(reference.Path))
{
assemblies.Add(reference.Path);
}
}
return assemblies;
}
private static HashSet<string> GetWebsiteLocalAssemblies(Project project)
{
var assemblies = new HashSet<string>(PathComparer.Default);
AssemblyReferences references = project.Object.References;
foreach (AssemblyReference reference in references)
{
// For websites only include bin assemblies
if (reference.ReferencedProject == null &&
reference.ReferenceKind == AssemblyReferenceType.AssemblyReferenceBin &&
File.Exists(reference.FullPath))
{
assemblies.Add(reference.FullPath);
}
}
return assemblies;
}
public static MsBuildProject AsMSBuildProject(this Project project)
{
return ProjectCollection.GlobalProjectCollection.GetLoadedProjects(project.FullName).FirstOrDefault() ??
ProjectCollection.GlobalProjectCollection.LoadProject(project.FullName);
}
/// <summary>
/// Returns the unique name of the specified project including all solution folder names containing it.
/// </summary>
/// <remarks>
/// This is different from the DTE Project.UniqueName property, which is the absolute path to the project file.
/// </remarks>
public static string GetCustomUniqueName(this Project project)
{
if (project.IsWebSite())
{
// website projects always have unique name
return project.Name;
}
else
{
Stack<string> nameParts = new Stack<string>();
Project cursor = project;
nameParts.Push(cursor.GetName());
// walk up till the solution root
while (cursor.ParentProjectItem != null && cursor.ParentProjectItem.ContainingProject != null)
{
cursor = cursor.ParentProjectItem.ContainingProject;
nameParts.Push(cursor.GetName());
}
return String.Join("\\", nameParts);
}
}
public static bool IsParentProjectExplicitlyUnsupported(this Project project)
{
if (project.ParentProjectItem == null || project.ParentProjectItem.ContainingProject == null)
{
// this project is not a child of another project
return false;
}
Project parentProject = project.ParentProjectItem.ContainingProject;
return parentProject.IsExplicitlyUnsupported();
}
public static void EnsureCheckedOutIfExists(this Project project, IFileSystem fileSystem, string path)
{
var fullPath = fileSystem.GetFullPath(path);
if (fileSystem.FileExists(path) &&
project.DTE.SourceControl != null &&
project.DTE.SourceControl.IsItemUnderSCC(fullPath) &&
!project.DTE.SourceControl.IsItemCheckedOut(fullPath))
{
// Check out the item
project.DTE.SourceControl.CheckOutItem(fullPath);
}
}
/// <summary>
/// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1
/// This is used for displaying in the projects combo box.
/// </summary>
public static string GetDisplayName(this Project project, ISolutionManager solutionManager)
{
return GetDisplayName(project, solutionManager.GetProjectSafeName);
}
/// <summary>
/// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1, but it uses Name instead of SafeName from Solution Manager.
/// </summary>
public static string GetDisplayName(this Project project)
{
return GetDisplayName(project, p => p.Name);
}
private static string GetDisplayName(this Project project, Func<Project, string> nameSelector)
{
string name = nameSelector(project);
if (project.IsWebSite())
{
name = PathHelper.SmartTruncate(name, 40);
}
return name;
}
private class PathComparer : IEqualityComparer<string>
{
public static readonly PathComparer Default = new PathComparer();
public bool Equals(string x, string y)
{
return Path.GetFileName(x).Equals(Path.GetFileName(y));
}
public int GetHashCode(string obj)
{
return Path.GetFileName(obj).GetHashCode();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using AllReady.Areas.Admin.Models.Validators;
using AllReady.Controllers;
using AllReady.DataAccess;
using AllReady.Models;
using AllReady.Security;
using AllReady.Services;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Features.Variance;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using AllReady.Security.Middleware;
namespace AllReady
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("version.json")
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add Application Insights data collection services to the services container.
services.AddApplicationInsightsTelemetry(Configuration);
// Add Entity Framework services to the services container.
var ef = services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage"));
services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection"));
services.Configure<EmailSettings>(Configuration.GetSection("Email"));
services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData"));
services.Configure<GeneralSettings>(Configuration.GetSection("General"));
// Add CORS support
services.AddCors(options =>
{
options.AddPolicy("allReady",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 10;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = false;
options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
})
.AddEntityFrameworkStores<AllReadyContext>()
.AddDefaultTokenProviders();
// Add Authorization rules for the app
services.AddAuthorization(options =>
{
options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin"));
options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin"));
});
// Add MVC services to the services container.
services.AddMvc();
// configure IoC support
var container = CreateIoCContainer(services);
return container.Resolve<IServiceProvider>();
}
private IContainer CreateIoCContainer(IServiceCollection services)
{
// todo: move these to a proper autofac module
// Register application services.
services.AddSingleton((x) => Configuration);
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IAllReadyDataAccess, AllReadyDataAccessEF7>();
services.AddTransient<IDetermineIfATaskIsEditable, DetermineIfATaskIsEditable>();
services.AddTransient<IValidateEventDetailModels, EventEditModelValidator>();
services.AddTransient<ITaskSummaryModelValidator, TaskSummaryModelValidator>();
services.AddTransient<IItineraryEditModelValidator, ItineraryEditModelValidator>();
services.AddTransient<IOrganizationEditModelValidator, OrganizationEditModelValidator>();
services.AddSingleton<IImageService, ImageService>();
//services.AddSingleton<GeoService>();
services.AddTransient<SampleDataGenerator>();
if (Configuration["Data:Storage:EnableAzureQueueService"] == "true")
{
// This setting is false by default. To enable queue processing you will
// need to override the setting in your user secrets or env vars.
services.AddTransient<IQueueStorageService, QueueStorageService>();
}
else
{
// this writer service will just write to the default logger
services.AddTransient<IQueueStorageService, FakeQueueWriterService>();
}
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterSource(new ContravariantRegistrationSource());
containerBuilder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces();
containerBuilder.RegisterAssemblyTypes(typeof(Startup).Assembly).AsImplementedInterfaces();
containerBuilder.Register<SingleInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
containerBuilder.Register<MultiInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
});
//Populate the container with services that were previously registered
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return container;
}
// Configure is called after ConfigureServices is called.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context,
IConfiguration configuration)
{
// todo: in RC update we can read from a logging.json config file
loggerFactory.AddConsole((category, level) =>
{
if (category.StartsWith("Microsoft."))
{
return level >= LogLevel.Information;
}
return true;
});
if (env.IsDevelopment())
{
// this will go to the VS output window
loggerFactory.AddDebug((category, level) =>
{
if (category.StartsWith("Microsoft."))
{
return level >= LogLevel.Information;
}
return true;
});
}
// CORS support
app.UseCors("allReady");
// Configure the HTTP request pipeline.
var usCultureInfo = new CultureInfo("en-US");
app.UseRequestLocalization(new RequestLocalizationOptions
{
SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }),
SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo })
});
// Add Application Insights to the request pipeline to track HTTP request telemetry data.
app.UseApplicationInsightsRequestTelemetry();
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseExceptionHandler("/Home/Error");
}
// Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
app.UseApplicationInsightsExceptionTelemetry();
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
// Add token-based protection to the request inject pipeline
app.UseTokenProtection(new TokenProtectedResourceOptions
{
Path = "/api/request",
PolicyName = "api-request-injest"
});
// Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
if (Configuration["Authentication:Facebook:AppId"] != null)
{
var options = new FacebookOptions
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"],
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name"
};
options.Scope.Add("email");
app.UseFacebookAuthentication(options);
}
if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
{
var options = new MicrosoftAccountOptions
{
ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
};
app.UseMicrosoftAccountAuthentication(options);
}
if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
{
var options = new TwitterOptions
{
ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
};
app.UseTwitterAuthentication(options);
}
if (Configuration["Authentication:Google:ClientId"] != null)
{
var options = new GoogleOptions
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
};
app.UseGoogleAuthentication(options);
}
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}");
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
// Add sample data and test admin accounts if specified in Config.Json.
// for production applications, this should either be set to false or deleted.
if (env.IsDevelopment() || env.IsEnvironment("Staging"))
{
context.Database.Migrate();
}
if (Configuration["SampleData:InsertSampleData"] == "true")
{
sampleData.InsertTestData();
}
if (Configuration["SampleData:InsertTestUsers"] == "true")
{
await sampleData.CreateAdminUser();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Collections;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class represents a single task.
/// </summary>
/// <owner>rgoel</owner>
public class BuildTask
{
#region Member Data
// The task XML element, if this is a persisted target.
private XmlElement taskElement = null;
// This is the "Condition" attribute on the task element.
private XmlAttribute conditionAttribute = null;
// This is the "ContinueOnError" attribute on the task element.
private XmlAttribute continueOnErrorAttribute = null;
// The target to which this task belongs.
private Target parentTarget= null;
// The name of the task.
private string taskName = String.Empty;
// If this is a persisted task element, this boolean tells us whether
// it came from the main project file or an imported project file.
private bool importedFromAnotherProject = false;
// This is the optional host object for this particular task. The actual task
// object will get passed this host object, and can communicate with it as it
// wishes. Although it is declared generically as an "Object" here, the actual
// task will cast it to whatever it expects.
private ITaskHost hostObject = null;
#endregion
#region Constructors
/// <summary>
/// This constructor initializes a persisted task from an existing task
/// element which exists either in the main project file or one of the
/// imported files.
/// </summary>
/// <param name="taskElement"></param>
/// <param name="parentTarget"></param>
/// <param name="importedFromAnotherProject"></param>
/// <owner>rgoel</owner>
internal BuildTask
(
XmlElement taskElement,
Target parentTarget,
bool importedFromAnotherProject
)
{
// Make sure a valid node has been given to us.
error.VerifyThrow(taskElement != null, "Need a valid XML node.");
// Make sure a valid target has been given to us.
error.VerifyThrow(parentTarget != null, "Need a valid target parent.");
this.taskElement = taskElement;
this.parentTarget = parentTarget;
this.conditionAttribute = null;
this.continueOnErrorAttribute = null;
this.importedFromAnotherProject = importedFromAnotherProject;
// Loop through all the attributes on the task element.
foreach (XmlAttribute taskAttribute in taskElement.Attributes)
{
switch (taskAttribute.Name)
{
case XMakeAttributes.condition:
this.conditionAttribute = taskAttribute;
break;
case XMakeAttributes.continueOnError:
this.continueOnErrorAttribute = taskAttribute;
break;
// this only makes sense in the context of the new OM,
// so just ignore it.
case XMakeAttributes.msbuildRuntime:
// do nothing
break;
// this only makes sense in the context of the new OM,
// so just ignore it.
case XMakeAttributes.msbuildArchitecture:
// do nothing
break;
}
}
this.taskName = taskElement.Name;
}
/// <summary>
/// Default constructor. This is not allowed, because it leaves the
/// BuildTask in a bad state. But we have to have it, otherwise FXCop
/// complains.
/// </summary>
/// <owner>rgoel</owner>
private BuildTask
(
)
{
// Not allowed.
}
#endregion
#region Properties
/// <summary>
/// Read-only accessor for XML element representing this task.
/// </summary>
/// <value></value>
/// <owner>RGoel</owner>
internal XmlElement TaskXmlElement
{
get
{
return this.taskElement;
}
}
/// <summary>
/// Accessor for the task's "name" element.
/// </summary>
/// <owner>RGoel</owner>
public string Name
{
get
{
return this.taskName;
}
}
/// <summary>
/// Accessor for the task's "condition".
/// </summary>
/// <owner>RGoel</owner>
public string Condition
{
get
{
return (this.conditionAttribute == null) ? String.Empty : this.conditionAttribute.Value;
}
set
{
// If this Task object is not actually represented by a
// task element in the project file, then do not allow
// the caller to set the condition.
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotSetCondition");
// If this task was imported from another project, we don't allow modifying it.
error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject,
"CannotModifyImportedProjects");
this.conditionAttribute = ProjectXmlUtilities.SetOrRemoveAttribute(taskElement, XMakeAttributes.condition, value);
this.MarkTaskAsDirty();
}
}
/// <summary>
/// Accessor for the task's "ContinueOnError".
/// </summary>
/// <owner>RGoel</owner>
public bool ContinueOnError
{
get
{
Expander expander = new Expander(parentTarget.ParentProject.evaluatedProperties, parentTarget.ParentProject.evaluatedItemsByName);
// NOTE: if the ContinueOnError attribute contains an item metadata reference, this property is meaningless
// because we are unable to batch -- this property will always be 'false' in that case
if ((continueOnErrorAttribute != null) &&
ConversionUtilities.ConvertStringToBool
(
expander.ExpandAllIntoString(continueOnErrorAttribute.Value, continueOnErrorAttribute)
))
{
return true;
}
else
{
return false;
}
}
set
{
// If this Task object is not actually represented by a
// task element in the project file, then do not allow
// the caller to set the attribute.
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotSetContinueOnError");
// If this task was imported from another project, we don't allow modifying it.
error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject,
"CannotModifyImportedProjects");
if (value)
{
this.taskElement.SetAttribute(XMakeAttributes.continueOnError, "true");
}
else
{
// Set the new "ContinueOnError" attribute on the task element.
this.taskElement.SetAttribute(XMakeAttributes.continueOnError, "false");
}
this.continueOnErrorAttribute = this.taskElement.Attributes[XMakeAttributes.continueOnError];
this.MarkTaskAsDirty();
}
}
/// <summary>
/// System.Type object corresponding to the task class that implements
/// the functionality that runs this task object.
/// </summary>
/// <owner>RGoel</owner>
public Type Type
{
get
{
// put verify throw for target name
ErrorUtilities.VerifyThrow(this.ParentTarget != null, "ParentTarget should not be null");
Engine parentEngine = this.ParentTarget.ParentProject.ParentEngine;
Project parentProject = this.ParentTarget.ParentProject;
string projectFileOfTaskNode = XmlUtilities.GetXmlNodeFile(taskElement, parentProject.FullFileName);
BuildEventContext taskContext = new BuildEventContext
(
parentProject.ProjectBuildEventContext.NodeId,
this.ParentTarget.Id,
parentProject.ProjectBuildEventContext.ProjectContextId,
parentProject.ProjectBuildEventContext.TaskId
);
int handleId = parentEngine.EngineCallback.CreateTaskContext(parentProject, ParentTarget, null, taskElement,
EngineCallback.inProcNode, taskContext);
EngineLoggingServices loggingServices = parentEngine.LoggingServices;
TaskExecutionModule taskExecutionModule = parentEngine.NodeManager.TaskExecutionModule;
TaskEngine taskEngine = new TaskEngine(taskElement, null,
projectFileOfTaskNode, parentProject.FullFileName, loggingServices, handleId, taskExecutionModule, taskContext);
ErrorUtilities.VerifyThrowInvalidOperation(taskEngine.FindTask(),
"MissingTaskError", taskName, parentEngine.ToolsetStateMap[ParentTarget.ParentProject.ToolsVersion].ToolsPath);
return taskEngine.TaskClass.Type;
}
}
/// <summary>
/// Accessor for the "host object" for this task.
/// </summary>
/// <owner>RGoel</owner>
public ITaskHost HostObject
{
get
{
return this.hostObject;
}
set
{
this.hostObject = value;
}
}
/// <summary>
/// Accessor for parent Target object.
/// </summary>
/// <value></value>
/// <owner>RGoel</owner>
internal Target ParentTarget
{
get
{
return this.parentTarget;
}
set
{
this.parentTarget = value;
}
}
#endregion
#region Methods
/// <summary>
/// This retrieves the list of all parameter names from the element
/// node of this task. Note that it excludes anything that a specific
/// property is exposed for or that isn't valid here (Name, Condition,
/// ContinueOnError).
///
/// Note that if there are none, it returns string[0], rather than null,
/// as it makes writing foreach statements over the return value so
/// much simpler.
/// </summary>
/// <returns></returns>
/// <owner>rgoel</owner>
public string[] GetParameterNames()
{
if (this.taskElement == null)
{
return new string[0];
}
ArrayList list = new ArrayList();
foreach (XmlAttribute attrib in this.taskElement.Attributes)
{
string attributeValue = attrib.Name;
if (!XMakeAttributes.IsSpecialTaskAttribute(attributeValue))
{
list.Add(attributeValue);
}
}
return (string[])list.ToArray(typeof(string));
}
/// <summary>
/// This retrieves an arbitrary attribute from the task element. These
/// are attributes that the project author has placed on the task element
/// that have no meaning to MSBuild other than that they get passed to the
/// task itself as arguments.
/// </summary>
/// <owner>RGoel</owner>
public string GetParameterValue
(
string attributeName
)
{
// You can only request the value of user-defined attributes. The well-known
// ones, like "ContinueOnError" for example, are accessed through other means.
error.VerifyThrowArgument(!XMakeAttributes.IsSpecialTaskAttribute(attributeName),
"CannotAccessKnownAttributes", attributeName);
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotUseParameters");
// If this is a persisted Task, grab the attribute directly from the
// task element.
return taskElement.GetAttribute(attributeName) ?? string.Empty;
}
/// <summary>
/// This sets an arbitrary attribute on the task element. These
/// are attributes that the project author has placed on the task element
/// that get passed in to the task.
///
/// This optionally escapes the parameter value so it will be treated as a literal.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="parameterValue"></param>
/// <param name="treatParameterValueAsLiteral"></param>
/// <owner>RGoel</owner>
public void SetParameterValue
(
string parameterName,
string parameterValue,
bool treatParameterValueAsLiteral
)
{
this.SetParameterValue(parameterName, treatParameterValueAsLiteral ? EscapingUtilities.Escape(parameterValue) : parameterValue);
}
/// <summary>
/// This sets an arbitrary attribute on the task element. These
/// are attributes that the project author has placed on the task element
/// that get passed in to the task.
/// </summary>
/// <owner>RGoel</owner>
public void SetParameterValue
(
string parameterName,
string parameterValue
)
{
// You can only set the value of user-defined attributes. The well-known
// ones, like "ContinueOnError" for example, are accessed through other means.
error.VerifyThrowArgument(!XMakeAttributes.IsSpecialTaskAttribute(parameterName),
"CannotAccessKnownAttributes", parameterName);
// If this task was imported from another project, we don't allow modifying it.
error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject,
"CannotModifyImportedProjects");
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotUseParameters");
// If this is a persisted Task, set the attribute directly on the
// task element.
taskElement.SetAttribute(parameterName, parameterValue);
this.MarkTaskAsDirty();
}
/// <summary>
/// Adds an Output tag to this task element
/// </summary>
/// <param name="taskParameter"></param>
/// <param name="itemName"></param>
/// <owner>LukaszG</owner>
public void AddOutputItem(string taskParameter, string itemName)
{
AddOutputItem(taskParameter, itemName, null);
}
/// <summary>
/// Adds an Output tag to this task element, with a condition
/// </summary>
/// <param name="taskParameter"></param>
/// <param name="itemName"></param>
/// <param name="condition">May be null</param>
internal void AddOutputItem(string taskParameter, string itemName, string condition)
{
// If this task was imported from another project, we don't allow modifying it.
error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject,
"CannotModifyImportedProjects");
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotUseParameters");
XmlElement newOutputElement = this.taskElement.OwnerDocument.CreateElement(XMakeElements.output, XMakeAttributes.defaultXmlNamespace);
newOutputElement.SetAttribute(XMakeAttributes.taskParameter, taskParameter);
newOutputElement.SetAttribute(XMakeAttributes.itemName, itemName);
if (condition != null)
{
newOutputElement.SetAttribute(XMakeAttributes.condition, condition);
}
this.taskElement.AppendChild(newOutputElement);
this.MarkTaskAsDirty();
}
/// <summary>
/// Adds an Output tag to this task element
/// </summary>
/// <param name="taskParameter"></param>
/// <param name="propertyName"></param>
/// <owner>LukaszG</owner>
public void AddOutputProperty(string taskParameter, string propertyName)
{
// If this task was imported from another project, we don't allow modifying it.
error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject,
"CannotModifyImportedProjects");
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotUseParameters");
XmlElement newOutputElement = this.taskElement.OwnerDocument.CreateElement(XMakeElements.output, XMakeAttributes.defaultXmlNamespace);
newOutputElement.SetAttribute(XMakeAttributes.taskParameter, taskParameter);
newOutputElement.SetAttribute(XMakeAttributes.propertyName, propertyName);
this.taskElement.AppendChild(newOutputElement);
this.MarkTaskAsDirty();
}
/// <summary>
/// Runs the task associated with this object.
/// </summary>
/// <owner>RGoel</owner>
public bool Execute
(
)
{
error.VerifyThrowInvalidOperation(this.taskElement != null,
"CannotExecuteUnassociatedTask");
error.VerifyThrowInvalidOperation(this.parentTarget != null,
"CannotExecuteUnassociatedTask");
return this.parentTarget.ExecuteOneTask(this.taskElement, this.HostObject);
}
/// <summary>
/// Indicates that something has changed within the task element, so the project
/// needs to be saved and re-evaluated at next build. Send the "dirtiness"
/// notification up the chain.
/// </summary>
/// <owner>RGoel</owner>
private void MarkTaskAsDirty
(
)
{
// This is a change to the contents of the target.
this.ParentTarget?.MarkTargetAsDirty();
}
#endregion
}
}
| |
using System;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Base class for services that support HTTP verbs.
/// </summary>
/// <typeparam name="TRequest">The request class that the descendent class
/// is responsible for processing.</typeparam>
[Obsolete("Use the New API (ServiceStack.ServiceInterface.Service) for future services. See: https://github.com/ServiceStack/ServiceStack/wiki/New-Api")]
public abstract class RestServiceBase<TRequest>
: ServiceBase<TRequest>,
IRestGetService<TRequest>,
IRestPutService<TRequest>,
IRestPostService<TRequest>,
IRestDeleteService<TRequest>,
IRestPatchService<TRequest>
{
/// <summary>
/// What gets run when the request is sent to AsyncOneWay endpoint.
/// For a REST service the OnPost() method is called.
/// </summary>
protected override object Run(TRequest request)
{
return OnPost(request);
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// GET verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the GET
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnGet(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Get(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnGet(request));
}
catch (Exception ex)
{
var result = HandleException(RequestContext.Get<IHttpRequest>(), request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PUT verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PUT
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPut(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Put(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPut(request));
}
catch (Exception ex)
{
var result = HandleException(RequestContext.Get<IHttpRequest>(), request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// POST verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the POST
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPost(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Post(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPost(request));
}
catch (Exception ex)
{
var result = HandleException(RequestContext.Get<IHttpRequest>(), request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// DELETE verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the DELETE
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnDelete(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Delete(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnDelete(request));
}
catch (Exception ex)
{
var result = HandleException(RequestContext.Get<IHttpRequest>(), request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PATCH verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PATCH
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPatch(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Patch(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPatch(request));
}
catch (Exception ex)
{
var result = HandleException(RequestContext.Get<IHttpRequest>(), request, ex);
if (result == null) throw;
return result;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
public enum TestEnum
{
VALUE_0,
VALUE_1
}
public class TestGenericComparer<T> : Comparer<T>
{
public TestGenericComparer() : base() { }
public override int Compare(T x, T y)
{
if (!(x is ValueType))
{
// reference type
Object ox = x as Object;
Object oy = y as Object;
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
}
if (x is IComparable<T>)
{
IComparable<T> comparer = x as IComparable<T>;
return comparer.CompareTo(y);
}
if (x is IComparable)
{
IComparable comparer = x as IComparable;
return comparer.CompareTo(y);
}
throw new ArgumentException();
}
}
public class TestClass : IComparable<TestClass>
{
public int Value;
public TestClass(int value)
{
Value = value;
}
public int CompareTo(TestClass other)
{
return this.Value - other.Value;
}
}
public class TestClass1 : IComparable
{
public int Value;
public TestClass1(int value)
{
Value = value;
}
public int CompareTo(object obj)
{
TestClass1 other = obj as TestClass1;
if (other != null)
{
return Value - other.Value;
}
if (obj is int)
{
int i = (int)obj;
return Value - i;
}
throw new ArgumentException("Must be instance of TestClass1 or Int32");
}
}
/// <summary>
/// System.Collections.IComparer.Compare(System.Object,System.Object)
/// </summary>
public class ComparerCompare2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && 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: Call Compare to compare two value type instance");
try
{
IComparer comparer = new TestGenericComparer<ValueType>() as IComparer;
retVal = VerificationHelper(comparer, 1, 2, -1, "001.1") && retVal;
retVal = VerificationHelper(comparer, 2, 1, 1, "001.2") && retVal;
retVal = VerificationHelper(comparer, 1, 1, 0, "001.3") && retVal;
retVal = VerificationHelper(comparer, 1.0, 2.0, -1, "001.4") && retVal;
retVal = VerificationHelper(comparer, 1, (int)TestEnum.VALUE_0, 1, "001.5") && retVal;
retVal = VerificationHelper(comparer, 1, (int)TestEnum.VALUE_1, 0, "001.6") && retVal;
retVal = VerificationHelper(comparer, 'a', 'A', 32, "001.7") && retVal;
retVal = VerificationHelper(comparer, 'a', 'a', 0, "001.8") && retVal;
retVal = VerificationHelper(comparer, 'A', 'a', -32, "001.9") && retVal;
comparer = new TestGenericComparer<int>() as IComparer;
retVal = VerificationHelper(comparer, 1, 2, -1, "001.10") && retVal;
retVal = VerificationHelper(comparer, 2, 1, 1, "001.11") && retVal;
retVal = VerificationHelper(comparer, 1, 1, 0, "001.12") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Compare with one or both parameters are null reference");
try
{
IComparer comparer = new TestGenericComparer<TestClass>() as IComparer;
retVal = VerificationHelper(comparer, null, new TestClass(1), -1, "002.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), null, 1, "002.2") && retVal;
retVal = VerificationHelper(comparer, null, null, 0, "002.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Compare when T implements IComparable<T>");
try
{
IComparer comparer = new TestGenericComparer<TestClass>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass(0), new TestClass(1), -1, "003.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), new TestClass(0), 1, "003.2") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), new TestClass(1), 0, "003.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Compare when T implements IComparable");
try
{
IComparer comparer = new TestGenericComparer<TestClass1>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass1(0), new TestClass1(1), -1, "004.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), new TestClass1(0), 1, "004.2") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), new TestClass1(1), 0, "004.3") && retVal;
comparer = new TestGenericComparer<Object>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass1(0), 1, -1, "004.4") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), 0, 1, "004.5") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), 1, 0, "004.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentException should be thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
try
{
TestGenericComparer<ComparerCompare2> comparer = new TestGenericComparer<ComparerCompare2>();
IComparer icompare = comparer as IComparer;
icompare.Compare(new ComparerCompare2(), new ComparerCompare2());
TestLibrary.TestFramework.LogError("101.1", "ArgumentException is not thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentException should be thrown when x is of a type that cannot be cast to type T");
try
{
TestGenericComparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
IComparer icompare = comparer as IComparer;
icompare.Compare('a', new TestClass1(1));
TestLibrary.TestFramework.LogError("102.1", "ArgumentException is not thrown when x is of a type that cannot be cast to type T");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when y is of a type that cannot be cast to type T");
try
{
TestGenericComparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
IComparer icompare = comparer as IComparer;
icompare.Compare(new TestClass1(1), 'a');
TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown when y is of a type that cannot be cast to type T");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ComparerCompare2 test = new ComparerCompare2();
TestLibrary.TestFramework.BeginTestCase("ComparerCompare2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(IComparer comparer, object x, object y, int expected, string errorno)
{
bool retVal = true;
int actual = comparer.Compare(x, y);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorno, "Compare returns unexpected value");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] x = " + x + ", y = " + y + ", expected = " + expected + ", actual = " + actual);
retVal = false;
}
return retVal;
}
#endregion
}
| |
namespace More.Windows.Input
{
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
public class AsyncNamedCommandTTest
{
[Theory]
[MemberData( nameof( IdData ) )]
public void new_named_data_item_command_should_set_id( Func<string, AsyncNamedCommand<object>> @new )
{
// arrange
var id = "42";
// act
var command = @new( id );
// assert
command.Id.Should().Be( id );
}
[Theory]
[MemberData( nameof( NameData ) )]
public void new_named_item_command_should_not_allow_null_name( Func<string, AsyncNamedCommand<object>> test )
{
// arrange
var name = default( string );
// act
Action @new = () => test( name );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( name ) );
}
[Theory]
[MemberData( nameof( NameData ) )]
public void new_named_item_command_should_not_allow_empty_name( Func<string, AsyncNamedCommand<object>> test )
{
// arrange
var name = "";
// act
Action @new = () => test( name );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( name ) );
}
[Theory]
[MemberData( nameof( NameData ) )]
public void new_named_item_command_should_set_name( Func<string, AsyncNamedCommand<object>> @new )
{
// arrange
var name = "Test";
// act
var command = @new( name );
// assert
command.Name.Should().Be( name );
}
[Theory]
[MemberData( nameof( ExecuteMethodData ) )]
public void new_named_item_command_should_not_allow_null_execute_method( Func<Func<object, Task>, AsyncNamedCommand<object>> test )
{
// arrange
var executeAsyncMethod = default( Func<object, Task> );
// act
Action @new = () => test( executeAsyncMethod );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( executeAsyncMethod ) );
}
[Theory]
[MemberData( nameof( CanExecuteMethodData ) )]
public void new_named_item_command_should_not_allow_null_can_execute_method( Func<Func<object, bool>, AsyncNamedCommand<object>> test )
{
// arrange
var canExecuteMethod = default( Func<object, bool> );
// act
Action @new = () => test( canExecuteMethod );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( canExecuteMethod ) );
}
[Theory]
[InlineData( null )]
[InlineData( "" )]
public void name_should_not_allow_null_or_empty( string value )
{
// arrange
var command = new AsyncNamedCommand<object>( "Test", p => Task.FromResult( 0 ) );
// act
Action setName = () => command.Name = value;
// assert
setName.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( value ) );
}
[Fact]
public void description_should_not_allow_null()
{
// arrange
var value = default( string );
var command = new AsyncNamedCommand<object>( "Test", p => Task.FromResult( 0 ) );
// act
Action setDescription = () => command.Description = value;
// assert
setDescription.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( value ) );
}
[Fact]
public void name_should_write_expected_value()
{
// arrange
var name = "Test";
var command = new AsyncNamedCommand<object>( "Default", p => Task.FromResult( 0 ) );
command.MonitorEvents();
// act
command.Name = name;
// assert
command.Name.Should().Be( name );
command.ShouldRaisePropertyChangeFor( c => c.Name );
}
[Fact]
public void description_should_write_expected_value()
{
// arrange
var description = "Test";
var command = new AsyncNamedCommand<object>( "Test", p => Task.FromResult( 0 ) );
command.MonitorEvents();
// act
command.Description = description;
// assert
command.Description.Should().Be( description );
command.ShouldRaisePropertyChangeFor( c => c.Description );
}
[Fact]
public void id_should_write_expected_value()
{
// arrange
var id = "42";
var command = new AsyncNamedCommand<object>( "Test", p => Task.FromResult( 0 ) );
command.MonitorEvents();
// act
command.Id = id;
// assert
command.Id.Should().Be( id );
command.ShouldRaisePropertyChangeFor( c => c.Id );
}
public static IEnumerable<object[]> IdData
{
get
{
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( id => new AsyncNamedCommand<object>( id, "Test", p => Task.FromResult( 0 ) ) ) };
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( id => new AsyncNamedCommand<object>( id, "Test", p => Task.FromResult( 0 ), p => true ) ) };
}
}
public static IEnumerable<object[]> NameData
{
get
{
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( name => new AsyncNamedCommand<object>( name, p => Task.FromResult( 0 ) ) ) };
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( name => new AsyncNamedCommand<object>( "1", name, p => Task.FromResult( 0 ) ) ) };
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( name => new AsyncNamedCommand<object>( name, p => Task.FromResult( 0 ), p => true ) ) };
yield return new object[] { new Func<string, AsyncNamedCommand<object>>( name => new AsyncNamedCommand<object>( "1", name, p => Task.FromResult( 0 ), p => true ) ) };
}
}
public static IEnumerable<object[]> ExecuteMethodData
{
get
{
yield return new object[] { new Func<Func<object, Task>, AsyncNamedCommand<object>>( execute => new AsyncNamedCommand<object>( "Test", execute ) ) };
yield return new object[] { new Func<Func<object, Task>, AsyncNamedCommand<object>>( execute => new AsyncNamedCommand<object>( "1", "Test", execute ) ) };
yield return new object[] { new Func<Func<object, Task>, AsyncNamedCommand<object>>( execute => new AsyncNamedCommand<object>( "Test", execute, p => true ) ) };
yield return new object[] { new Func<Func<object, Task>, AsyncNamedCommand<object>>( execute => new AsyncNamedCommand<object>( "1", "Test", execute, p => true ) ) };
}
}
public static IEnumerable<object[]> CanExecuteMethodData
{
get
{
yield return new object[] { new Func<Func<object, bool>, AsyncNamedCommand<object>>( canExecute => new AsyncNamedCommand<object>( "Test", p => Task.FromResult( 0 ), canExecute ) ) };
yield return new object[] { new Func<Func<object, bool>, AsyncNamedCommand<object>>( canExecute => new AsyncNamedCommand<object>( "1", "Test", p => Task.FromResult( 0 ), canExecute ) ) };
}
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>MobileDeviceConstant</c> resource.</summary>
public sealed partial class MobileDeviceConstantName : gax::IResourceName, sys::IEquatable<MobileDeviceConstantName>
{
/// <summary>The possible contents of <see cref="MobileDeviceConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>mobileDeviceConstants/{criterion_id}</c>.</summary>
Criterion = 1,
}
private static gax::PathTemplate s_criterion = new gax::PathTemplate("mobileDeviceConstants/{criterion_id}");
/// <summary>Creates a <see cref="MobileDeviceConstantName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="MobileDeviceConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static MobileDeviceConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new MobileDeviceConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="MobileDeviceConstantName"/> with the pattern <c>mobileDeviceConstants/{criterion_id}</c>
/// .
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="MobileDeviceConstantName"/> constructed from the provided ids.
/// </returns>
public static MobileDeviceConstantName FromCriterion(string criterionId) =>
new MobileDeviceConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </returns>
public static string Format(string criterionId) => FormatCriterion(criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </returns>
public static string FormatCriterion(string criterionId) =>
s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="MobileDeviceConstantName"/> if successful.</returns>
public static MobileDeviceConstantName Parse(string mobileDeviceConstantName) =>
Parse(mobileDeviceConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="MobileDeviceConstantName"/> if successful.</returns>
public static MobileDeviceConstantName Parse(string mobileDeviceConstantName, bool allowUnparsed) =>
TryParse(mobileDeviceConstantName, allowUnparsed, out MobileDeviceConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MobileDeviceConstantName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mobileDeviceConstantName, out MobileDeviceConstantName result) =>
TryParse(mobileDeviceConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MobileDeviceConstantName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mobileDeviceConstantName, bool allowUnparsed, out MobileDeviceConstantName result)
{
gax::GaxPreconditions.CheckNotNull(mobileDeviceConstantName, nameof(mobileDeviceConstantName));
gax::TemplatedResourceName resourceName;
if (s_criterion.TryParseName(mobileDeviceConstantName, out resourceName))
{
result = FromCriterion(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(mobileDeviceConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private MobileDeviceConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CriterionId = criterionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="MobileDeviceConstantName"/> class from the component parts of
/// pattern <c>mobileDeviceConstants/{criterion_id}</c>
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public MobileDeviceConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as MobileDeviceConstantName);
/// <inheritdoc/>
public bool Equals(MobileDeviceConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(MobileDeviceConstantName a, MobileDeviceConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(MobileDeviceConstantName a, MobileDeviceConstantName b) => !(a == b);
}
public partial class MobileDeviceConstant
{
/// <summary>
/// <see cref="gagvr::MobileDeviceConstantName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal MobileDeviceConstantName ResourceNameAsMobileDeviceConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::MobileDeviceConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::MobileDeviceConstantName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal MobileDeviceConstantName MobileDeviceConstantName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::MobileDeviceConstantName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Text.Tests
{
public class EncodingGetChars1
{
#region Positive Testcases
[Fact]
public void PosTest1()
{
PositiveTestString(Encoding.UTF8, "TestString", new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00A");
}
[Fact]
public void PosTest2()
{
PositiveTestString(Encoding.UTF8, "", new byte[] { }, "00B");
}
[Fact]
public void PosTest3()
{
PositiveTestString(Encoding.UTF8, "FooBA\u0400R", new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, "00C");
}
[Fact]
public void PosTest4()
{
PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, "00D");
}
[Fact]
public void PosTest5()
{
PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, "00E");
}
[Fact]
public void PosTest6()
{
PositiveTestString(Encoding.UTF8, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, "00F");
}
[Fact]
public void PosTest7()
{
PositiveTestString(Encoding.UTF8, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD", new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, "00G");
}
[Fact]
public void PosTest8()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "TestTest", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, "00H");
}
[Fact]
public void PosTest9()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD", new byte[] { 176 }, "00I");
}
[Fact]
public void PosTest10()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD", new byte[] { 196 }, "00J");
}
[Fact]
public void PosTest11()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, "00K");
}
[Fact]
public void PosTest12()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "\u0130", new byte[] { 196, 176 }, "00L");
}
[Fact]
public void PosTest13()
{
PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD", new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, "0A2");
}
[Fact]
public void PosTest14()
{
PositiveTestString(Encoding.Unicode, "TestString\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0, 45 }, "00A3");
}
[Fact]
public void PosTest15()
{
PositiveTestString(Encoding.Unicode, "", new byte[] { }, "00B3");
}
[Fact]
public void PosTest16()
{
PositiveTestString(Encoding.Unicode, "FooBA\u0400R", new byte[] { 70, 0, 111, 0, 111, 0, 66, 0, 65, 0, 0, 4, 82, 0 }, "00C3");
}
[Fact]
public void PosTest17()
{
PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", new byte[] { 192, 0, 110, 0, 105, 0, 109, 0, 97, 0, 0, 3, 108, 0 }, "00D3");
}
[Fact]
public void PosTest18()
{
PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 3, 216, 117, 221, 84, 0, 101, 0, 115, 0, 116, 0 }, "00E3");
}
[Fact]
public void PosTest19()
{
PositiveTestString(Encoding.Unicode, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F3");
}
[Fact]
public void PosTest20()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0 }, "00G3");
}
[Fact]
public void PosTest21()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 117, 221 }, "00H3");
}
[Fact]
public void PosTest22()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 3, 216 }, "00I3");
}
[Fact]
public void PosTest23()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "\uFFFD\uFFFD", new byte[] { 3, 216, 84 }, "00J3");
}
[Fact]
public void PosTest24()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221, 3, 216, 117, 221 }, "00K3");
}
[Fact]
public void PosTest25()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "\u0130", new byte[] { 48, 1 }, "00L3");
}
[Fact]
public void PosTest26()
{
PositiveTestString(Encoding.GetEncoding("utf-16"), "\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221 }, "0A23");
}
[Fact]
public void PosTest27()
{
PositiveTestString(Encoding.BigEndianUnicode, "TestString\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00A4");
}
[Fact]
public void PosTest28()
{
PositiveTestString(Encoding.BigEndianUnicode, "", new byte[] { }, "00B4");
}
[Fact]
public void PosTest29()
{
PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R\uFFFD", new byte[] { 0, 70, 0, 111, 0, 111, 0, 66, 0, 65, 4, 0, 0, 82, 70 }, "00C4");
}
[Fact]
public void PosTest30()
{
PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", new byte[] { 0, 192, 0, 110, 0, 105, 0, 109, 0, 97, 3, 0, 0, 108 }, "00D4");
}
[Fact]
public void PosTest31()
{
PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 216, 3, 221, 117, 0, 84, 0, 101, 0, 115, 0, 116 }, "00E4");
}
[Fact]
public void PosTest32()
{
PositiveTestString(Encoding.BigEndianUnicode, "\0Te\nst\0\t\0T\u000Fest\0\uFFFD", new byte[] { 0, 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F4");
}
[Fact]
public void PosTest33()
{
PositiveTestString(Encoding.BigEndianUnicode, "TestTest", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116 }, "00G4");
}
[Fact]
public void PosTest34()
{
PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 221, 117 }, "00H4");
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void PosTest35()
{
PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 216, 3 }, "00I4");
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void PosTest36()
{
PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uFFFD\uFFFD", new byte[] { 216, 3, 48 }, "00J4");
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void PosTest37()
{
PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117, 216, 3, 221, 117 }, "00K4");
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void PosTest38()
{
PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\u0130", new byte[] { 1, 48 }, "00L4");
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void PosTest39()
{
PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117 }, "0A24");
}
#endregion
#region Negative Testcases
[Fact]
public void NegTest1()
{
NegativeTestChars<ArgumentNullException>(new UTF8Encoding(), null, "00O");
}
[Fact]
public void NegTest2()
{
NegativeTestChars<ArgumentNullException>(new UnicodeEncoding(), null, "00O3");
}
[Fact]
public void NegTest3()
{
NegativeTestChars<ArgumentNullException>(new UnicodeEncoding(true, false), null, "00O4");
}
[Fact]
public void NegTest4()
{
NegativeTestChars2<ArgumentNullException>(new UTF8Encoding(), null, 0, 0, "00P");
}
[Fact]
public void NegTest5()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, -1, 1, "00P");
}
[Fact]
public void NegTest6()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 1, -1, "00Q");
}
[Fact]
public void NegTest7()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 0, 10, "00R");
}
[Fact]
public void NegTest8()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 3, 0, "00S");
}
[Fact]
public void NegTest9()
{
NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(), null, 0, 0, "00P3");
}
[Fact]
public void NegTest10()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, -1, 1, "00P3");
}
[Fact]
public void NegTest11()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 1, -1, "00Q3");
}
[Fact]
public void NegTest12()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 0, 10, "00R3");
}
[Fact]
public void NegTest13()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 3, 0, "00S3");
}
[Fact]
public void NegTest14()
{
NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(true, false), null, 0, 0, "00P4");
}
[Fact]
public void NegTest15()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, -1, 1, "00P4");
}
[Fact]
public void NegTest16()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 1, -1, "00Q4");
}
[Fact]
public void NegTest17()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 0, 10, "00R4");
}
[Fact]
public void NegTest18()
{
NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 3, 0, "00S4");
}
private static char[] s_output = new char[20];
[Fact]
public void NegTest19()
{
NegativeTestChars3<ArgumentNullException>(Encoding.UTF8, null, 0, 0, s_output, 0, "00T");
}
[Fact]
public void NegTest20()
{
NegativeTestChars3<ArgumentNullException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, null, 0, "00U");
}
[Fact]
public void NegTest21()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V");
}
[Fact]
public void NegTest22()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W");
}
[Fact]
public void NegTest23()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X");
}
[Fact]
public void NegTest24()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y");
}
[Fact]
public void NegTest25()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z");
}
[Fact]
public void NegTest26()
{
NegativeTestChars3<ArgumentException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A0");
}
[Fact]
public void NegTest27()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A1");
}
[Fact]
public void NegTest28()
{
NegativeTestChars3<ArgumentNullException>(Encoding.Unicode, null, 0, 0, s_output, 0, "00T3");
}
[Fact]
public void NegTest29()
{
NegativeTestChars3<ArgumentNullException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, null, 0, "00U3");
}
[Fact]
public void NegTest30()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V3");
}
[Fact]
public void NegTest31()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W3");
}
[Fact]
public void NegTest32()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X3");
}
[Fact]
public void NegTest33()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y3");
}
[Fact]
public void NegTest34()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z3");
}
[Fact]
public void NegTest35()
{
NegativeTestChars3<ArgumentException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A03");
}
[Fact]
public void NegTest36()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A13");
}
[Fact]
public void NegTest37()
{
NegativeTestChars3<ArgumentNullException>(Encoding.BigEndianUnicode, null, 0, 0, s_output, 0, "00T4");
}
[Fact]
public void NegTest38()
{
NegativeTestChars3<ArgumentNullException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, null, 0, "00U4");
}
[Fact]
public void NegTest39()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V4");
}
[Fact]
public void NegTest40()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W4");
}
[Fact]
public void NegTest41()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X4");
}
[Fact]
public void NegTest42()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y4");
}
[Fact]
public void NegTest43()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z4");
}
[Fact]
public void NegTest44()
{
NegativeTestChars3<ArgumentException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A04");
}
[Fact]
public void NegTest45()
{
NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A14");
}
#endregion
public void PositiveTestString(Encoding enc, string expected, byte[] bytes, string id)
{
char[] chars = enc.GetChars(bytes);
string str = new string(chars);
Assert.Equal(expected, str);
}
public void NegativeTestChars<T>(Encoding enc, byte[] bytes, string id) where T : Exception
{
Assert.Throws<T>(() =>
{
char[] chars = enc.GetChars(bytes);
string str = new string(chars);
});
}
public void NegativeTestChars2<T>(Encoding enc, byte[] bytes, int index, int count, string id) where T : Exception
{
Assert.Throws<T>(() =>
{
char[] chars = enc.GetChars(bytes, index, count);
string str = new string(chars);
});
}
public void NegativeTestChars3<T>(Encoding enc, byte[] bytes, int index, int count, char[] chars, int bIndex, string id)
where T : Exception
{
Assert.Throws<T>(() =>
{
int output = enc.GetChars(bytes, index, count, chars, bIndex);
string str = new string(chars);
});
}
}
}
| |
// cassandra-sharp - high performance .NET driver for Apache Cassandra
// Copyright (c) 2011-2013 Pierre Chalamet
//
// 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 CassandraSharp.Transport
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using CassandraSharp.CQLBinaryProtocol.Queries;
using CassandraSharp.Config;
using CassandraSharp.Exceptions;
using CassandraSharp.Extensibility;
using CassandraSharp.Utils;
internal sealed class LongRunningConnection : IConnection,
IDisposable
{
private const ushort MAX_STREAMID = 0x80;
private readonly Stack<ushort> _availableStreamIds = new Stack<ushort>();
private readonly TransportConfig _config;
private readonly KeyspaceConfig _keyspaceConfig;
private readonly IInstrumentation _instrumentation;
private readonly object _lock = new object();
private readonly ILogger _logger;
private readonly Queue<QueryInfo> _pendingQueries = new Queue<QueryInfo>();
private readonly Action<QueryInfo, IFrameReader, bool> _pushResult;
private readonly QueryInfo[] _queryInfos = new QueryInfo[MAX_STREAMID];
private readonly Task _queryWorker;
private readonly Task _responseWorker;
private readonly Socket _socket;
private readonly TcpClient _tcpClient;
private bool _isClosed;
public LongRunningConnection(IPAddress address, TransportConfig config, KeyspaceConfig keyspaceConfig, ILogger logger, IInstrumentation instrumentation)
{
try
{
for (ushort streamId = 0; streamId < MAX_STREAMID; ++streamId)
{
_availableStreamIds.Push(streamId);
}
_config = config;
_keyspaceConfig = keyspaceConfig;
_logger = logger;
_instrumentation = instrumentation;
Endpoint = address;
DefaultConsistencyLevel = config.DefaultConsistencyLevel;
DefaultExecutionFlags = config.DefaultExecutionFlags;
_tcpClient = new TcpClient
{
ReceiveTimeout = _config.ReceiveTimeout,
SendTimeout = _config.SendTimeout,
NoDelay = true,
LingerState = { Enabled = true, LingerTime = 0 },
};
if(0 < _config.ConnectionTimeout)
{
// TODO: refactor this and this probably is not robust in front of error
IAsyncResult asyncResult = _tcpClient.BeginConnect(address, _config.Port, null, null);
bool success = asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_config.ConnectionTimeout), true);
if (! success)
{
throw new InvalidOperationException("Connection timeout occured.");
}
if (! _tcpClient.Connected)
{
_tcpClient.Close();
throw new InvalidOperationException("Can't connect to node.");
}
_tcpClient.EndConnect(asyncResult);
}
else
{
_tcpClient.Connect(address, _config.Port);
}
_socket = _tcpClient.Client;
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, _config.KeepAlive);
if (_config.KeepAlive && 0 != _config.KeepAliveTime)
{
SetTcpKeepAlive(_socket, _config.KeepAliveTime, 1000);
}
_pushResult = _config.ReceiveBuffering
? (Action<QueryInfo, IFrameReader, bool>)((qi, fr, a) => Task.Factory.StartNew(() => PushResult(qi, fr, a)))
: PushResult;
_responseWorker = Task.Factory.StartNew(() => RunWorker(ReadResponse), TaskCreationOptions.LongRunning);
_queryWorker = Task.Factory.StartNew(() => RunWorker(SendQuery), TaskCreationOptions.LongRunning);
// readify the connection
_logger.Debug("Readyfying connection for {0}", Endpoint);
//GetOptions();
ReadifyConnection();
_logger.Debug("Connection to {0} is ready", Endpoint);
}
catch (Exception ex)
{
Dispose();
_logger.Error("Failed building connection {0}", ex);
throw;
}
}
public IPAddress Endpoint { get; private set; }
public ConsistencyLevel DefaultConsistencyLevel { get; private set; }
public ExecutionFlags DefaultExecutionFlags { get; private set; }
public event EventHandler<FailureEventArgs> OnFailure;
public void Execute<T>(Action<IFrameWriter> writer, Func<IFrameReader, IEnumerable<T>> reader, InstrumentationToken token,
IObserver<T> observer)
{
QueryInfo queryInfo = new QueryInfo<T>(writer, reader, token, observer);
lock (_lock)
{
Monitor.Pulse(_lock);
if (_isClosed)
{
throw new OperationCanceledException();
}
_pendingQueries.Enqueue(queryInfo);
}
}
public void Dispose()
{
Close(null);
// wait for worker threads to gracefully shutdown
ExceptionExtensions.SafeExecute(() => _responseWorker.Wait());
ExceptionExtensions.SafeExecute(() => _queryWorker.Wait());
}
public static void SetTcpKeepAlive(Socket socket, int keepaliveTime, int keepaliveInterval)
{
if (Runtime.IsMono)
{
return;
}
// marshal the equivalent of the native structure into a byte array
byte[] inOptionValues = new byte[12];
int enable = 0 != keepaliveTime
? 1
: 0;
BitConverter.GetBytes(enable).CopyTo(inOptionValues, 0);
BitConverter.GetBytes(keepaliveTime).CopyTo(inOptionValues, 4);
BitConverter.GetBytes(keepaliveInterval).CopyTo(inOptionValues, 8);
// write SIO_VALS to Socket IOControl
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
private void Close(Exception ex)
{
// already in close state ?
lock (_lock)
{
bool wasClosed = _isClosed;
_isClosed = true;
Monitor.PulseAll(_lock);
if (wasClosed)
{
return;
}
// abort all pending queries
OperationCanceledException canceledException = new OperationCanceledException();
for (int i = 0; i < _queryInfos.Length; ++i)
{
var queryInfo = _queryInfos[i];
if (null != queryInfo)
{
queryInfo.NotifyError(canceledException);
_instrumentation.ClientTrace(queryInfo.Token, EventType.Cancellation);
_queryInfos[i] = null;
}
}
foreach (var queryInfo in _pendingQueries)
{
queryInfo.NotifyError(canceledException);
_instrumentation.ClientTrace(queryInfo.Token, EventType.Cancellation);
}
_pendingQueries.Clear();
}
// we have now the guarantee this instance is destroyed once
_tcpClient.SafeDispose();
if (null != ex && null != OnFailure)
{
_logger.Fatal("Failed with error : {0}", ex);
FailureEventArgs failureEventArgs = new FailureEventArgs(ex);
OnFailure(this, failureEventArgs);
}
// release event to release observer
OnFailure = null;
}
private void RunWorker(Action action)
{
try
{
action();
}
catch (Exception ex)
{
HandleError(ex);
}
}
private void SendQuery()
{
while (true)
{
QueryInfo queryInfo;
lock (_lock)
{
while (!_isClosed && 0 == _pendingQueries.Count)
{
Monitor.Wait(_lock);
}
if (_isClosed)
{
Monitor.Pulse(_lock);
return;
}
queryInfo = _pendingQueries.Dequeue();
}
try
{
// acquire the global lock to write the request
InstrumentationToken token = queryInfo.Token;
bool tracing = 0 != (token.ExecutionFlags & ExecutionFlags.ServerTracing);
using (BufferingFrameWriter bufferingFrameWriter = new BufferingFrameWriter(tracing))
{
queryInfo.Write(bufferingFrameWriter);
ushort streamId;
lock (_lock)
{
while (!_isClosed && 0 == _availableStreamIds.Count)
{
Monitor.Wait(_lock);
}
if (_isClosed)
{
queryInfo.NotifyError(new OperationCanceledException());
_instrumentation.ClientTrace(token, EventType.Cancellation);
Monitor.Pulse(_lock);
return;
}
streamId = _availableStreamIds.Pop();
}
_logger.Debug("Starting writing frame for stream {0}@{1}", streamId, Endpoint);
_instrumentation.ClientTrace(token, EventType.BeginWrite);
_queryInfos[streamId] = queryInfo;
bufferingFrameWriter.SendFrame(streamId, _socket);
_logger.Debug("Done writing frame for stream {0}@{1}", streamId, Endpoint);
_instrumentation.ClientTrace(token, EventType.EndWrite);
}
}
catch (Exception ex)
{
queryInfo.NotifyError(ex);
if (IsStreamInBadState(ex))
{
throw;
}
}
}
}
private void ReadResponse()
{
while (true)
{
IFrameReader frameReader = null;
try
{
frameReader = _config.ReceiveBuffering
? new BufferingFrameReader(_socket)
: new StreamingFrameReader(_socket);
QueryInfo queryInfo = GetAndReleaseQueryInfo(frameReader);
_pushResult(queryInfo, frameReader, _config.ReceiveBuffering);
}
catch (Exception ex)
{
frameReader.SafeDispose();
throw;
}
}
}
private QueryInfo GetAndReleaseQueryInfo(IFrameReader frameReader)
{
QueryInfo queryInfo;
ushort streamId = frameReader.StreamId;
lock (_lock)
{
Monitor.Pulse(_lock);
if (_isClosed)
{
throw new OperationCanceledException();
}
queryInfo = _queryInfos[streamId];
_queryInfos[streamId] = null;
_availableStreamIds.Push(streamId);
}
return queryInfo;
}
private void PushResult(QueryInfo queryInfo, IFrameReader frameReader, bool isAsync)
{
try
{
_instrumentation.ClientTrace(queryInfo.Token, EventType.BeginRead);
try
{
if (null != frameReader.ResponseException)
{
throw frameReader.ResponseException;
}
queryInfo.Push(frameReader);
}
catch (Exception ex)
{
queryInfo.NotifyError(ex);
if (IsStreamInBadState(ex))
{
throw;
}
}
_instrumentation.ClientTrace(queryInfo.Token, EventType.EndRead);
InstrumentationToken token = queryInfo.Token;
if (0 != (token.ExecutionFlags & ExecutionFlags.ServerTracing))
{
_instrumentation.ServerTrace(token, frameReader.TraceId);
}
}
catch (Exception ex)
{
if (isAsync)
{
HandleError(ex);
}
}
finally
{
if (isAsync)
{
frameReader.SafeDispose();
}
}
}
private static bool IsStreamInBadState(Exception ex)
{
bool isFatal = ex is SocketException || ex is IOException || ex is TimeOutException;
return isFatal;
}
private void HandleError(Exception ex)
{
Close(ex);
}
private void GetOptions()
{
var obsOptions = new CreateOptionsQuery(this, ConsistencyLevel.ONE, ExecutionFlags.None).AsFuture();
obsOptions.Wait();
}
private void ReadifyConnection()
{
var obsReady = new ReadyQuery(this, ConsistencyLevel.ONE, ExecutionFlags.None, _config.CqlVersion).AsFuture();
bool authenticate = obsReady.Result.Single();
if (authenticate)
{
Authenticate();
}
if (!string.IsNullOrWhiteSpace(_keyspaceConfig.Name))
{
SetupKeyspace();
}
}
private void Authenticate()
{
if (null == _config.User || null == _config.Password)
{
throw new InvalidCredentialException();
}
var obsAuth = new AuthenticateQuery(this, ConsistencyLevel.ONE, ExecutionFlags.None, _config.User, _config.Password).AsFuture();
if (!obsAuth.Result.Single())
{
throw new InvalidCredentialException();
}
}
private void SetupKeyspace()
{
var setKeyspaceQuery = new SetKeyspaceQuery(this, _keyspaceConfig.Name);
try
{
setKeyspaceQuery.AsFuture().Wait();
}
catch
{
new CreateKeyspaceQuery(
this,
_keyspaceConfig.Name,
_keyspaceConfig.Replication.Options,
_keyspaceConfig.DurableWrites).AsFuture().Wait();
setKeyspaceQuery.AsFuture().Wait();
}
_logger.Debug("Set default keyspace to {0}", _keyspaceConfig.Name);
}
private abstract class QueryInfo
{
protected QueryInfo(InstrumentationToken token)
{
Token = token;
}
public InstrumentationToken Token { get; private set; }
public abstract void Write(IFrameWriter frameWriter);
public abstract void Push(IFrameReader frameReader);
public abstract void NotifyError(Exception ex);
}
private class QueryInfo<T> : QueryInfo
{
public QueryInfo(Action<IFrameWriter> writer, Func<IFrameReader, IEnumerable<T>> reader,
InstrumentationToken token, IObserver<T> observer)
: base(token)
{
Writer = writer;
Reader = reader;
Observer = observer;
}
private Func<IFrameReader, IEnumerable<T>> Reader { get; set; }
private Action<IFrameWriter> Writer { get; set; }
private IObserver<T> Observer { get; set; }
public override void Write(IFrameWriter frameWriter)
{
Writer(frameWriter);
}
public override void Push(IFrameReader frameReader)
{
IEnumerable<T> data = Reader(frameReader);
foreach (T datum in data)
{
Observer.OnNext(datum);
}
Observer.OnCompleted();
}
public override void NotifyError(Exception ex)
{
Observer.OnError(ex);
}
}
}
}
| |
/*
* 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.Collections.Generic;
using NUnit.Framework;
using OpenSim.Framework;
using OpenSim.Tests.Common;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.Framework.Scenes;
using Nini.Config;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenMetaverse;
using System;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for LSL_Api
/// </summary>
[TestFixture, LongRunning]
public class LSL_ApiTest
{
private const double VECTOR_COMPONENT_ACCURACY = 0.0000005d;
private const double ANGLE_ACCURACY_IN_RADIANS = 1E-6;
private LSL_Api m_lslApi;
[SetUp]
public void SetUp()
{
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
Scene scene = new SceneHelpers().SetupScene();
SceneObjectPart part = SceneHelpers.AddSceneObject(scene).RootPart;
XEngine.XEngine engine = new XEngine.XEngine();
engine.Initialise(initConfigSource);
engine.AddRegion(scene);
m_lslApi = new LSL_Api();
m_lslApi.Initialize(engine, part, null);
}
[Test]
public void TestllAngleBetween()
{
TestHelpers.InMethod();
CheckllAngleBetween(new Vector3(1, 0, 0), 0, 1, 1);
CheckllAngleBetween(new Vector3(1, 0, 0), 90, 1, 1);
CheckllAngleBetween(new Vector3(1, 0, 0), 180, 1, 1);
CheckllAngleBetween(new Vector3(0, 1, 0), 0, 1, 1);
CheckllAngleBetween(new Vector3(0, 1, 0), 90, 1, 1);
CheckllAngleBetween(new Vector3(0, 1, 0), 180, 1, 1);
CheckllAngleBetween(new Vector3(0, 0, 1), 0, 1, 1);
CheckllAngleBetween(new Vector3(0, 0, 1), 90, 1, 1);
CheckllAngleBetween(new Vector3(0, 0, 1), 180, 1, 1);
CheckllAngleBetween(new Vector3(1, 1, 1), 0, 1, 1);
CheckllAngleBetween(new Vector3(1, 1, 1), 90, 1, 1);
CheckllAngleBetween(new Vector3(1, 1, 1), 180, 1, 1);
CheckllAngleBetween(new Vector3(1, 0, 0), 0, 1.6f, 1.8f);
CheckllAngleBetween(new Vector3(1, 0, 0), 90, 0.3f, 3.9f);
CheckllAngleBetween(new Vector3(1, 0, 0), 180, 8.8f, 7.4f);
CheckllAngleBetween(new Vector3(0, 1, 0), 0, 9.8f, -9.4f);
CheckllAngleBetween(new Vector3(0, 1, 0), 90, 8.4f, -8.2f);
CheckllAngleBetween(new Vector3(0, 1, 0), 180, 0.4f, -5.8f);
CheckllAngleBetween(new Vector3(0, 0, 1), 0, -6.8f, 3.4f);
CheckllAngleBetween(new Vector3(0, 0, 1), 90, -3.6f, 5.6f);
CheckllAngleBetween(new Vector3(0, 0, 1), 180, -3.8f, 1.1f);
CheckllAngleBetween(new Vector3(1, 1, 1), 0, -7.7f, -2.0f);
CheckllAngleBetween(new Vector3(1, 1, 1), 90, -3.0f, -9.1f);
CheckllAngleBetween(new Vector3(1, 1, 1), 180, -7.9f, -8.0f);
}
private void CheckllAngleBetween(Vector3 axis,float originalAngle, float denorm1, float denorm2)
{
Quaternion rotation1 = Quaternion.CreateFromAxisAngle(axis, 0);
Quaternion rotation2 = Quaternion.CreateFromAxisAngle(axis, ToRadians(originalAngle));
rotation1 *= denorm1;
rotation2 *= denorm2;
double deducedAngle = FromLslFloat(m_lslApi.llAngleBetween(ToLslQuaternion(rotation2), ToLslQuaternion(rotation1)));
Assert.That(deducedAngle, Is.EqualTo(ToRadians(originalAngle)).Within(ANGLE_ACCURACY_IN_RADIANS), "TestllAngleBetween check fail");
}
#region Conversions to and from LSL_Types
private float ToRadians(double degrees)
{
return (float)(Math.PI * degrees / 180);
}
// private double FromRadians(float radians)
// {
// return radians * 180 / Math.PI;
// }
private double FromLslFloat(LSL_Types.LSLFloat lslFloat)
{
return lslFloat.value;
}
// private LSL_Types.LSLFloat ToLslFloat(double value)
// {
// return new LSL_Types.LSLFloat(value);
// }
// private Quaternion FromLslQuaternion(LSL_Types.Quaternion lslQuaternion)
// {
// return new Quaternion((float)lslQuaternion.x, (float)lslQuaternion.y, (float)lslQuaternion.z, (float)lslQuaternion.s);
// }
private LSL_Types.Quaternion ToLslQuaternion(Quaternion quaternion)
{
return new LSL_Types.Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}
#endregion
[Test]
// llRot2Euler test.
public void TestllRot2Euler()
{
TestHelpers.InMethod();
// 180, 90 and zero degree rotations.
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, 0.0f, 0.707107f, 0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, 0.0f, 1.0f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, 0.0f, 0.707107f, -0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.707107f, 0.0f, 0.0f, 0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.5f, -0.5f, 0.5f, 0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, -0.707107f, 0.707107f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, -0.5f, 0.5f, -0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(1.0f, 0.0f, 0.0f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.707107f, -0.707107f, 0.0f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, -1.0f, 0.0f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.707107f, -0.707107f, 0.0f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.707107f, 0.0f, 0.0f, -0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.5f, -0.5f, -0.5f, -0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, -0.707107f, -0.707107f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, -0.5f, -0.5f, 0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, -0.707107f, 0.0f, 0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, -0.5f, 0.5f, 0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.707107f, 0.0f, 0.707107f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, 0.5f, 0.5f, -0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.0f, -0.707107f, 0.0f, -0.707107f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, -0.5f, -0.5f, -0.5f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.707107f, 0.0f, -0.707107f, 0.0f));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.5f, 0.5f, -0.5f, 0.5f));
// A couple of messy rotations.
CheckllRot2Euler(new LSL_Types.Quaternion(1.0f, 5.651f, -3.1f, 67.023f));
CheckllRot2Euler(new LSL_Types.Quaternion(0.719188f, -0.408934f, -0.363998f, -0.427841f));
// Some deliberately malicious rotations (intended on provoking singularity errors)
// The "f" suffexes are deliberately omitted.
CheckllRot2Euler(new LSL_Types.Quaternion(0.50001f, 0.50001f, 0.50001f, 0.50001f));
// More malice. The "f" suffixes are deliberately omitted.
CheckllRot2Euler(new LSL_Types.Quaternion(-0.701055, 0.092296, 0.701055, -0.092296));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.183005, -0.683010, 0.183005, 0.683010));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.430460, -0.560982, 0.430460, 0.560982));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.701066, 0.092301, -0.701066, 0.092301));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.183013, -0.683010, 0.183013, 0.683010));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.183005, -0.683014, -0.183005, -0.683014));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.353556, 0.612375, 0.353556, -0.612375));
CheckllRot2Euler(new LSL_Types.Quaternion(0.353554, -0.612385, -0.353554, 0.612385));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.560989, 0.430450, 0.560989, -0.430450));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.183013, 0.683009, -0.183013, 0.683009));
CheckllRot2Euler(new LSL_Types.Quaternion(0.430457, -0.560985, -0.430457, 0.560985));
CheckllRot2Euler(new LSL_Types.Quaternion(0.353552, 0.612360, -0.353552, -0.612360));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.499991, 0.500003, 0.499991, -0.500003));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.353555, -0.612385, -0.353555, -0.612385));
CheckllRot2Euler(new LSL_Types.Quaternion(0.701066, -0.092301, -0.701066, 0.092301));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.499991, 0.500007, 0.499991, -0.500007));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.683002, 0.183016, -0.683002, 0.183016));
CheckllRot2Euler(new LSL_Types.Quaternion(0.430458, 0.560982, 0.430458, 0.560982));
CheckllRot2Euler(new LSL_Types.Quaternion(0.499991, -0.500003, -0.499991, 0.500003));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.183009, 0.683011, -0.183009, 0.683011));
CheckllRot2Euler(new LSL_Types.Quaternion(0.560975, -0.430457, 0.560975, -0.430457));
CheckllRot2Euler(new LSL_Types.Quaternion(0.701055, 0.092300, 0.701055, 0.092300));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.560990, 0.430459, -0.560990, 0.430459));
CheckllRot2Euler(new LSL_Types.Quaternion(-0.092302, -0.701059, -0.092302, -0.701059));
}
/// <summary>
/// Check an llRot2Euler conversion.
/// </summary>
/// <remarks>
/// Testing Rot2Euler this way instead of comparing against expected angles because
/// 1. There are several ways to get to the original Quaternion. For example a rotation
/// of PI and -PI will give the same result. But PI and -PI aren't equal.
/// 2. This method checks to see if the calculated angles from a quaternion can be used
/// to create a new quaternion to produce the same rotation.
/// However, can't compare the newly calculated quaternion against the original because
/// once again, there are multiple quaternions that give the same result. For instance
/// <X, Y, Z, S> == <-X, -Y, -Z, -S>. Additionally, the magnitude of S can be changed
/// and will still result in the same rotation if the values for X, Y, Z are also changed
/// to compensate.
/// However, if two quaternions represent the same rotation, then multiplying the first
/// quaternion by the conjugate of the second, will give a third quaternion representing
/// a zero rotation. This can be tested for by looking at the X, Y, Z values which should
/// be zero.
/// </remarks>
/// <param name="rot"></param>
private void CheckllRot2Euler(LSL_Types.Quaternion rot)
{
// Call LSL function to convert quaternion rotaion to euler radians.
LSL_Types.Vector3 eulerCalc = m_lslApi.llRot2Euler(rot);
// Now use the euler radians to recalculate a new quaternion rotation
LSL_Types.Quaternion newRot = m_lslApi.llEuler2Rot(eulerCalc);
// Multiple original quaternion by conjugate of quaternion calculated with angles.
LSL_Types.Quaternion check = rot * new LSL_Types.Quaternion(-newRot.x, -newRot.y, -newRot.z, newRot.s);
Assert.AreEqual(0.0, check.x, VECTOR_COMPONENT_ACCURACY, "TestllRot2Euler X bounds check fail");
Assert.AreEqual(0.0, check.y, VECTOR_COMPONENT_ACCURACY, "TestllRot2Euler Y bounds check fail");
Assert.AreEqual(0.0, check.z, VECTOR_COMPONENT_ACCURACY, "TestllRot2Euler Z bounds check fail");
}
[Test]
public void TestllVecNorm()
{
TestHelpers.InMethod();
// Check special case for normalizing zero vector.
CheckllVecNorm(new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), new LSL_Types.Vector3(0.0d, 0.0d, 0.0d));
// Check various vectors.
CheckllVecNorm(new LSL_Types.Vector3(10.0d, 25.0d, 0.0d), new LSL_Types.Vector3(0.371391d, 0.928477d, 0.0d));
CheckllVecNorm(new LSL_Types.Vector3(1.0d, 0.0d, 0.0d), new LSL_Types.Vector3(1.0d, 0.0d, 0.0d));
CheckllVecNorm(new LSL_Types.Vector3(-90.0d, 55.0d, 2.0d), new LSL_Types.Vector3(-0.853128d, 0.521356d, 0.018958d));
CheckllVecNorm(new LSL_Types.Vector3(255.0d, 255.0d, 255.0d), new LSL_Types.Vector3(0.577350d, 0.577350d, 0.577350d));
}
public void CheckllVecNorm(LSL_Types.Vector3 vec, LSL_Types.Vector3 vecNormCheck)
{
// Call LSL function to normalize the vector.
LSL_Types.Vector3 vecNorm = m_lslApi.llVecNorm(vec);
// Check each vector component against expected result.
Assert.AreEqual(vecNorm.x, vecNormCheck.x, VECTOR_COMPONENT_ACCURACY, "TestllVecNorm vector check fail on x component");
Assert.AreEqual(vecNorm.y, vecNormCheck.y, VECTOR_COMPONENT_ACCURACY, "TestllVecNorm vector check fail on y component");
Assert.AreEqual(vecNorm.z, vecNormCheck.z, VECTOR_COMPONENT_ACCURACY, "TestllVecNorm vector check fail on z component");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public enum FrameSettingsRenderType
{
Camera,
CustomOrBakedReflection,
RealtimeReflection
}
public struct FrameSettingsHistory : IDebugData
{
static readonly string[] foldoutNames = { "Rendering", "Lighting", "Async Compute", "Light Loop" };
static readonly string[] columnNames = { "Debug", "Sanitized", "Overridden", "Default" };
static readonly Dictionary<FrameSettingsField, FrameSettingsFieldAttribute> attributes;
static Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>> attributesGroup = new Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>>();
// due to strange management of Scene view cameras, all camera of type Scene will share same FrameSettingsHistory
#if UNITY_EDITOR
internal static Camera sceneViewCamera;
#endif
internal static Dictionary<Camera, FrameSettingsHistory> frameSettingsHistory = new Dictionary<Camera, FrameSettingsHistory>();
public FrameSettingsRenderType defaultType;
public FrameSettings overridden;
public FrameSettingsOverrideMask customMask;
public FrameSettings sanitazed;
public FrameSettings debug;
Camera camera; //ref for DebugMenu retrieval only
static bool s_PossiblyInUse;
public static bool enabled
{
get
{
// The feature is enabled when either DebugWindow or DebugRuntimeUI
// are displayed. When none are displayed, the feature remain in use
// as long as there is one renderer that have debug modification.
// We use s_PossiblyInUse to perform the check on the FrameSettingsHistory
// collection the less possible (only when we exited all the windows
// as long as there is modification).
if (!s_PossiblyInUse)
return s_PossiblyInUse = DebugManager.instance.displayEditorUI || DebugManager.instance.displayRuntimeUI;
else
return DebugManager.instance.displayEditorUI
|| DebugManager.instance.displayRuntimeUI
// a && (a = something) different than a &= something as if a is false something is not evaluated in second version
|| (s_PossiblyInUse && (s_PossiblyInUse = frameSettingsHistory.Values.Any(history => history.debug == history.sanitazed)));
}
}
/// <summary>Initialize data for FrameSettings panel of DebugMenu construction.</summary>
static FrameSettingsHistory()
{
attributes = new Dictionary<FrameSettingsField, FrameSettingsFieldAttribute>();
attributesGroup = new Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>>();
Type type = typeof(FrameSettingsField);
foreach (FrameSettingsField value in Enum.GetValues(type))
{
attributes[value] = type.GetField(Enum.GetName(type, value)).GetCustomAttribute<FrameSettingsFieldAttribute>();
}
}
/// <summary>Same than FrameSettings.AggregateFrameSettings but keep history of agregation in a collection for DebugMenu.
/// Aggregation is default with override of the renderer then sanitazed depending on supported features of hdrpasset. Then the DebugMenu override occurs.</summary>
/// <param name="aggregatedFrameSettings">The aggregated FrameSettings result.</param>
/// <param name="camera">The camera rendering.</param>
/// <param name="additionalData">Additional data of the camera rendering.</param>
/// <param name="hdrpAsset">HDRenderPipelineAsset contening default FrameSettings.</param>
public static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSettings, Camera camera, HDAdditionalCameraData additionalData, HDRenderPipelineAsset hdrpAsset)
=> AggregateFrameSettings(
ref aggregatedFrameSettings,
camera,
additionalData,
ref hdrpAsset.GetDefaultFrameSettings(additionalData?.defaultFrameSettings ?? FrameSettingsRenderType.Camera), //fallback on Camera for SceneCamera and PreviewCamera
hdrpAsset.currentPlatformRenderPipelineSettings
);
// Note: this version is the one tested as there is issue getting HDRenderPipelineAsset in batchmode in unit test framework currently.
/// <summary>Same than FrameSettings.AggregateFrameSettings but keep history of agregation in a collection for DebugMenu.
/// Aggregation is default with override of the renderer then sanitazed depending on supported features of hdrpasset. Then the DebugMenu override occurs.</summary>
/// <param name="aggregatedFrameSettings">The aggregated FrameSettings result.</param>
/// <param name="camera">The camera rendering.</param>
/// <param name="additionalData">Additional data of the camera rendering.</param>
/// <param name="defaultFrameSettings">Base framesettings to copy prior any override.</param>
/// <param name="supportedFeatures">Currently supported feature for the sanitazation pass.</param>
public static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSettings, Camera camera, HDAdditionalCameraData additionalData, ref FrameSettings defaultFrameSettings, RenderPipelineSettings supportedFeatures)
{
FrameSettingsHistory history = new FrameSettingsHistory
{
camera = camera,
defaultType = additionalData ? additionalData.defaultFrameSettings : FrameSettingsRenderType.Camera
};
aggregatedFrameSettings = defaultFrameSettings;
if (additionalData && additionalData.customRenderingSettings)
{
FrameSettings.Override(ref aggregatedFrameSettings, additionalData.renderingPathCustomFrameSettings, additionalData.renderingPathCustomFrameSettingsOverrideMask);
history.customMask = additionalData.renderingPathCustomFrameSettingsOverrideMask;
}
history.overridden = aggregatedFrameSettings;
FrameSettings.Sanitize(ref aggregatedFrameSettings, camera, supportedFeatures);
bool noHistory = !frameSettingsHistory.ContainsKey(camera);
bool updatedComponent = !noHistory && frameSettingsHistory[camera].sanitazed != aggregatedFrameSettings;
bool dirty = noHistory || updatedComponent;
history.sanitazed = aggregatedFrameSettings;
if (dirty)
history.debug = history.sanitazed;
else
{
history.debug = frameSettingsHistory[camera].debug;
// Ensure user is not trying to activate unsupported settings in DebugMenu
FrameSettings.Sanitize(ref history.debug, camera, supportedFeatures);
}
aggregatedFrameSettings = history.debug;
frameSettingsHistory[camera] = history;
}
static DebugUI.HistoryBoolField GenerateHistoryBoolField(HDRenderPipelineAsset hdrpAsset, ref FrameSettingsHistory frameSettings, FrameSettingsField field, FrameSettingsFieldAttribute attribute)
{
Camera camera = frameSettings.camera;
var renderType = frameSettings.defaultType;
string displayIndent = "";
for (int indent = 0; indent < attribute.indentLevel; ++indent)
displayIndent += " ";
return new DebugUI.HistoryBoolField
{
displayName = displayIndent + attribute.displayedName,
getter = () => frameSettingsHistory[camera].debug.IsEnabled(field),
setter = value =>
{
var tmp = frameSettingsHistory[camera]; //indexer with struct will create a copy
tmp.debug.SetEnabled(field, value);
frameSettingsHistory[camera] = tmp;
},
historyGetter = new Func<bool>[]
{
() => frameSettingsHistory[camera].sanitazed.IsEnabled(field),
() => frameSettingsHistory[camera].overridden.IsEnabled(field),
() => hdrpAsset.GetDefaultFrameSettings(renderType).IsEnabled(field)
}
};
}
static DebugUI.HistoryEnumField GenerateHistoryEnumField(HDRenderPipelineAsset hdrpAsset, ref FrameSettingsHistory frameSettings, FrameSettingsField field, FrameSettingsFieldAttribute attribute, Type autoEnum)
{
Camera camera = frameSettings.camera;
var renderType = frameSettings.defaultType;
string displayIndent = "";
for (int indent = 0; indent < attribute.indentLevel; ++indent)
displayIndent += " ";
return new DebugUI.HistoryEnumField
{
displayName = displayIndent + attribute.displayedName,
getter = () => frameSettingsHistory[camera].debug.IsEnabled(field) ? 1 : 0,
setter = value =>
{
var tmp = frameSettingsHistory[camera]; //indexer with struct will create a copy
tmp.debug.SetEnabled(field, value == 1);
frameSettingsHistory[camera] = tmp;
},
autoEnum = autoEnum,
// Contrarily to other enum of DebugMenu, we do not need to stock index as
// it can be computed again with data in the dedicated debug section of history
getIndex = () => frameSettingsHistory[camera].debug.IsEnabled(field) ? 1 : 0,
setIndex = (int a) => { },
historyIndexGetter = new Func<int>[]
{
() => frameSettingsHistory[camera].sanitazed.IsEnabled(field) ? 1 : 0,
() => frameSettingsHistory[camera].overridden.IsEnabled(field) ? 1 : 0,
() => hdrpAsset.GetDefaultFrameSettings(renderType).IsEnabled(field) ? 1 : 0
}
};
}
static ObservableList<DebugUI.Widget> GenerateHistoryArea(HDRenderPipelineAsset hdrpAsset, ref FrameSettingsHistory frameSettings, int groupIndex)
{
if (!attributesGroup.ContainsKey(groupIndex) || attributesGroup[groupIndex] == null)
attributesGroup[groupIndex] = attributes?.Where(pair => pair.Value?.group == groupIndex)?.OrderBy(pair => pair.Value.orderInGroup);
if (!attributesGroup.ContainsKey(groupIndex))
throw new ArgumentException("Unknown groupIndex");
var area = new ObservableList<DebugUI.Widget>();
foreach (var field in attributesGroup[groupIndex])
{
switch (field.Value.type)
{
case FrameSettingsFieldAttribute.DisplayType.BoolAsCheckbox:
area.Add(GenerateHistoryBoolField(hdrpAsset, ref frameSettings, field.Key, field.Value));
break;
case FrameSettingsFieldAttribute.DisplayType.BoolAsEnumPopup:
area.Add(GenerateHistoryEnumField(
hdrpAsset,
ref frameSettings,
field.Key,
field.Value,
RetrieveEnumTypeByField(field.Key)
));
break;
case FrameSettingsFieldAttribute.DisplayType.Others: // for now, skip other display settings. Add them if needed
break;
}
}
return area;
}
static DebugUI.Widget[] GenerateFrameSettingsPanelContent(HDRenderPipelineAsset hdrpAsset, ref FrameSettingsHistory frameSettings)
{
var panelContent = new DebugUI.Widget[foldoutNames.Length];
for (int index = 0; index < foldoutNames.Length; ++index)
{
panelContent[index] = new DebugUI.Foldout(foldoutNames[index], GenerateHistoryArea(hdrpAsset, ref frameSettings, index), columnNames);
}
return panelContent;
}
static void GenerateFrameSettingsPanel(string menuName, FrameSettingsHistory frameSettings)
{
HDRenderPipelineAsset hdrpAsset = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
var camera = frameSettings.camera;
List<DebugUI.Widget> widgets = new List<DebugUI.Widget>();
widgets.AddRange(GenerateFrameSettingsPanelContent(hdrpAsset, ref frameSettings));
var panel = DebugManager.instance.GetPanel(menuName, true, 1);
panel.children.Add(widgets.ToArray());
}
static Type RetrieveEnumTypeByField(FrameSettingsField field)
{
switch (field)
{
case FrameSettingsField.LitShaderMode: return typeof(LitShaderMode);
default: throw new ArgumentException("Unknow enum type for this field");
}
}
/// <summary>Register FrameSettingsHistory for DebugMenu</summary>
public static IDebugData RegisterDebug(Camera camera, HDAdditionalCameraData additionalCameraData)
{
HDRenderPipelineAsset hdrpAsset = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
Assertions.Assert.IsNotNull(hdrpAsset);
// complete frame settings history is required for displaying debug menu.
// AggregateFrameSettings will finish the registration if it is not yet registered
FrameSettings registering = new FrameSettings();
AggregateFrameSettings(ref registering, camera, additionalCameraData, hdrpAsset);
GenerateFrameSettingsPanel(camera.name, frameSettingsHistory[camera]);
#if UNITY_EDITOR
if (sceneViewCamera == null && camera.cameraType == CameraType.SceneView)
sceneViewCamera = camera;
#endif
return frameSettingsHistory[camera];
}
/// <summary>Unregister FrameSettingsHistory for DebugMenu</summary>
public static void UnRegisterDebug(Camera camera)
{
DebugManager.instance.RemovePanel(camera.name);
frameSettingsHistory.Remove(camera);
}
#if UNITY_EDITOR
/// <summary>Check if the common frameSettings for SceneViewCamera is already created.</summary>
public static bool isRegisteredSceneViewCamera(Camera camera) =>
camera.cameraType == CameraType.SceneView && sceneViewCamera != null && frameSettingsHistory.ContainsKey(sceneViewCamera);
#endif
/// <summary>Return a copy of the persistently stored data.</summary>
public static IDebugData GetPersistantDebugDataCopy(Camera camera) => frameSettingsHistory[camera];
void TriggerReset()
{
var tmp = frameSettingsHistory[camera];
tmp.debug = tmp.sanitazed; //erase immediately debug data as camera could be not rendered if not enabled.
frameSettingsHistory[camera] = this; //copy changed history to collection
}
Action IDebugData.GetReset() => TriggerReset;
}
}
| |
//----------------------------------------------------------------------//
// ___ ___ ___ ___ ___ ___ ________ ________ //
// |\ \ |\ \ / /|\ \ / /|\ \|\ ___ \|\ ____\ //
// \ \ \ \ \ \/ / | \ \ / / | \ \ \ \\ \ \ \ \___|_ //
// \ \ \ \ \ / / \ \ \/ / / \ \ \ \ \\ \ \ \_____ \ //
// \ \ \____ \/ / / \ \ / / \ \ \ \ \\ \ \|____|\ \ //
// \ \_______\__/ / / \ \__/ / \ \__\ \__\\ \__\____\_\ \ //
// \|_______|\___/ / \|__|/ \|__|\|__| \|__|\_________\//
// \|___|/ \|_________|//
// //
//----------------------------------------------------------------------//
// File : Building.cs //
// Description : Represents the data of a building //
// Original author : J.Klessens //
// Company : Lyvins //
// Project : LyvinOS //
// Created on : 26-2-2014 //
//----------------------------------------------------------------------//
// //
// Copyright (c) 2013, 2014 Lyvins //
// //
// 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. //
// //
//----------------------------------------------------------------------//
// //
// Prerequisites / Return Codes / Notes //
// //
//----------------------------------------------------------------------//
// //
// Tasks / Features / Bugs //
// ToDo: Commenting //
// //
//----------------------------------------------------------------------//
using System.Collections.Generic;
using LyvinDataStoreLib.Models;
using LyvinSystemLogicLib;
namespace LyvinDataStoreLib.LyvinLayoutData
{
/// <summary>
/// Represents the data of a building
/// </summary>
[TableName("building")]
[PrimaryKey("BuildingID")]
public class Building
{
/// <summary>
///
/// </summary>
public ulong BuildingID { get; set; }
/// <summary>
///
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string Status { get; set; }
/// <summary>
///
/// </summary>
[Ignore]public List<Room> Rooms { get; set; }
/// <summary>
///
/// </summary>
[Ignore]public List<Address> Addresses { get; set; }
/// <summary>
///
/// </summary>
public Building()
{
Rooms = new List<Room>();
Addresses = new List<Address>();
}
/// <summary>
///
/// </summary>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="status"></param>
public Building(string description, string name, string status)
{
Description = description;
Name = name;
Status = status;
}
/// <summary>
///
/// </summary>
/// <param name="address"></param>
public void AddAddress(Address address)
{
using (var lyvinDB = new Database("lyvinsdb"))
{
if ((lyvinDB.Exists<Building>(address.BuildingID)) && (address.BuildingID == BuildingID))
{
lyvinDB.Save(address);
Addresses.RemoveAll(a => a.AddressID == address.AddressID);
if (address.State == "CURRENT")
{
Addresses.Add(address);
}
}
else
{
ErrorManager.InvokeError("Database Error", "Trying to add address without building");
}
}
}
/// <summary>
///
/// </summary>
/// <param name="addressid"></param>
public void RemoveAddress(ulong addressid)
{
Addresses.RemoveAll(a => a.AddressID == addressid);
using (var lyvinDB = new Database("lyvinsdb"))
{
var address = lyvinDB.SingleOrDefault<Address>("SELECT * FROM address WHERE AddressID=@0",
addressid);
if (address == null)
return;
address.Status = "REMOVED";
lyvinDB.Save(address);
}
}
/// <summary>
///
/// </summary>
/// <param name="room"></param>
public void AddRoom(Room room)
{
using (var lyvinDB = new Database("lyvinsdb"))
{
if ((lyvinDB.Exists<Building>(room.BuildingID)) && (room.BuildingID == BuildingID))
{
lyvinDB.Save(room);
Rooms.RemoveAll(r => r.RoomID == room.RoomID);
if (room.Status == "CURRENT")
{
Rooms.Add(room);
}
}
else
{
ErrorManager.InvokeError("Database Error", "Trying to add room without building");
}
}
}
/// <summary>
///
/// </summary>
/// <param name="rooms"></param>
public void AddRooms(List<Room> rooms)
{
foreach (var room in rooms)
{
AddRoom(room);
}
}
/// <summary>
///
/// </summary>
/// <param name="roomid"></param>
public void RemoveRoom(ulong roomid)
{
Rooms.RemoveAll(r => r.RoomID == roomid);
using (var lyvinDB = new Database("lyvinsdb"))
{
var room = lyvinDB.SingleOrDefault<Room>("SELECT * FROM room WHERE RoomID=@0",
roomid);
if (room == null)
return;
room.Status = "REMOVED";
lyvinDB.Save(room);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
[Serializable]
public class ObjectPool
{
public GameObject ObjectToPool;
public string PoolName;
public int AmountToPool;
public bool ShouldExpand = true;
public ObjectPool() { }
public ObjectPool(GameObject prefab, string name, int amount, bool expandable = true)
{
ObjectToPool = prefab;
PoolName = name;
AmountToPool = amount;
ShouldExpand = expandable;
}
public void Initialize()
{
if (ObjectToPool != null)
{
Id = ObjectToPool.GetInstanceID();
Initialized = true;
}
}
public bool Initialized { get; private set; }
public int Id { get; private set; }
public GameObject ParentPoolObject { get; set; }
public LinkedList<GameObjectContainer> Items { get; } = new LinkedList<GameObjectContainer>();
public int Recycles { get; set; }
public int Created { get; set; }
public int Expands { get; set; }
}
public interface IPoolable
{
void Spawn();
void Despawn();
}
public class GameObjectContainer
{
public ObjectPool Pool;
public GameObject Object;
public List<IPoolable> PoolingEnabledComponents;
public int Cycles;
public int TimesSkipped;
public int TimesSelected;
public int Despawns;
public int Spawns;
public int ObjectId;
}
public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler Instance;
public string RootPoolName = "Pooled Objects";
public List<ObjectPool> Pools;
public Dictionary<int, GameObjectContainer> Map { get; } = new Dictionary<int, GameObjectContainer>();
void Awake()
{
Instance = this;
SceneManager.sceneLoaded += SceneManagerOnSceneLoaded;
}
private void SceneManagerOnSceneLoaded(Scene arg0, LoadSceneMode loadSceneMode)
{
Debug.Log("Resetting Object Pools");
Reset();
}
private void CreatePools()
{
foreach (var item in Pools)
{
for (int i = 0; i < item.AmountToPool; i++)
{
CreatePooledObject(item);
}
}
}
public void Reset()
{
foreach (var pool in Pools)
{
if(pool == null)
continue;
foreach (var item in pool.Items)
{
if(item == null)
continue;
if (item.Object != null)
{
Destroy(item.Object);
}
item.Object = null;
item.Pool = null;
item.PoolingEnabledComponents.Clear();
}
pool.Items.Clear();
pool.ParentPoolObject = null;
}
Map.Clear();
CreatePools();
}
/// <summary>
/// Find/Create the parent which pooled objects should be attached to.
/// </summary>
private GameObject GetParentPoolObject(string objectPoolName)
{
if (string.IsNullOrEmpty(objectPoolName))
objectPoolName = RootPoolName;
var parentObject = GameObject.Find(objectPoolName);
if (parentObject != null)
return parentObject;
parentObject = new GameObject
{
name = objectPoolName
};
if (objectPoolName == RootPoolName)
return parentObject;
var root = GameObject.Find(RootPoolName) ?? GetParentPoolObject(RootPoolName);
parentObject.transform.parent = root.transform;
return parentObject;
}
/// <summary>
/// Create a new item for a given pool
/// </summary>
private GameObjectContainer CreatePooledObject(ObjectPool pool)
{
if (pool.ObjectToPool == null)
{
throw new Exception($"Object pool entry '{pool.PoolName}' needs a prefab attached");
}
if (!pool.Initialized)
pool.Initialize();
var obj = Instantiate(pool.ObjectToPool);
obj.name = obj.name;
if (pool.ParentPoolObject == null)
pool.ParentPoolObject = GetParentPoolObject(pool.PoolName);
obj.transform.parent = pool.ParentPoolObject.transform;
obj.SetActive(false);
var container = new GameObjectContainer
{
Object = obj,
ObjectId = obj.GetInstanceID(),
Pool = pool,
PoolingEnabledComponents = obj.GetComponents<IPoolable>().ToList(),
};
Map.Add(obj.GetInstanceID(), container);
pool.Items.AddFirst(container);
pool.Created++;
return container;
}
/// <summary>
/// Create an instance of an GameObject prefab.
/// A replacment for 'Instantiate(...)'.
/// </summary>
/// <param name="prefab">A game object prefab to create an instance of</param>
/// <param name="position">The position of the spawned GameObject</param>
/// <param name="rotation">The rotation of the spawned GameObject</param>
/// <returns>pooled GameObject</returns>
public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation)
{
var id = prefab.GetInstanceID();
var pool = GetPoolForPrefab(id);
if (pool == null)
{
pool = new ObjectPool(prefab, prefab.name, 25);
//Debug.Log($"Dynamically creating pool for prefab {prefab.name}");
Pools.Add(pool);
//throw new Exception($"Unable to find object pool for type");
}
var container = FindFreePoolItem(pool);
if (container == null)
{
if (!pool.ShouldExpand)
return null;
container = CreatePooledObject(pool);
pool.Expands++;
}
else
{
pool.Recycles++;
}
container.Spawns++;
RecycleItem(container, position, rotation);
return container.Object;
}
/// <summary>
/// Return GameObject to the pool.
/// A replacement for 'Destroy(...)'.
/// </summary>
/// <param name="o"></param>
public void Despawn(GameObject o)
{
if (o == null)
return;
var container = GetContainer(o.GetInstanceID());
if (container != null)
{
container.Despawns++;
foreach (var c in container.PoolingEnabledComponents)
{
c.Despawn();
}
}
o.SetActive(false);
}
/// <summary>
/// Reset transform and call IPoolable.Spawn on components.
/// </summary>
private static void RecycleItem(GameObjectContainer container, Vector3 position, Quaternion rotation)
{
var t = container.Object.transform;
t.rotation = rotation;
t.position = position;
container.Object.SetActive(true);
container.Cycles++;
foreach (var c in container.PoolingEnabledComponents)
{
c.Spawn();
}
}
/// <summary>
/// Get an item from a given pool that is not being used.
/// </summary>
private GameObjectContainer FindFreePoolItem(ObjectPool pool)
{
for (int i = 0; i < pool.Items.Count; i++)
{
var node = pool.Items.First;
pool.Items.RemoveFirst();
pool.Items.AddLast(node);
// Clean out objects that no longer exist (because of scene unload etc)
var obj = node.Value.Object;
if (obj == null)
{
DestroyContainer(node.Value);
continue;
}
if (!obj.activeInHierarchy)
{
node.Value.TimesSelected++;
return node.Value;
}
node.Value.TimesSkipped++;
}
return null;
}
private void DestroyContainer(GameObjectContainer container)
{
container.Pool.Items.Remove(container);
Map.Remove(container.ObjectId);
}
private ObjectPool GetPoolForPrefab(int prefabInstanceId)
{
for (int i = 0; i < Pools.Count; i++)
{
var pool = Pools[i];
if (pool.Id == prefabInstanceId)
return pool;
}
return null;
}
private GameObjectContainer GetContainer(int gameObjectInstanceId)
{
GameObjectContainer container;
Map.TryGetValue(gameObjectInstanceId, out container);
return container;
}
}
| |
/*
insert license info here
*/
using System;
using System.Collections;
namespace Business.Data
{
/// <summary>
/// Generated by MyGeneration using the NHibernate Object Mapping template
/// </summary>
[Serializable]
public sealed class Cie10 : Business.BaseDataAccess
{
#region Private Members
private bool m_isChanged;
private int m_id;
private string m_capitulo;
private string m_grupocie10;
private string m_causa;
private string m_subcausa;
private string m_codigo;
private string m_nombre;
private string m_descripcap;
//private double m_modif;
#endregion
#region Default ( Empty ) Class Constuctor
/// <summary>
/// default constructor
/// </summary>
public Cie10()
{
m_id = 0;
m_capitulo = String.Empty;
m_grupocie10 = String.Empty;
m_causa = String.Empty;
m_subcausa = String.Empty;
m_codigo = String.Empty;
m_nombre = String.Empty;
m_descripcap = String.Empty;
//m_modif = new double();
}
#endregion // End of Default ( Empty ) Class Constuctor
#region Required Fields Only Constructor
/// <summary>
/// required (not null) fields only constructor
/// </summary>
public Cie10(
int id)
: this()
{
m_id = id;
m_capitulo = String.Empty;
m_grupocie10 = String.Empty;
m_causa = String.Empty;
m_subcausa = String.Empty;
m_codigo = String.Empty;
m_nombre = String.Empty;
m_descripcap = String.Empty;
//m_modif = null;
}
#endregion // End Required Fields Only Constructor
#region Public Properties
/// <summary>
///
/// </summary>
public int Id
{
get { return m_id; }
set
{
m_isChanged |= ( m_id != value );
m_id = value;
}
}
/// <summary>
///
/// </summary>
public string Capitulo
{
get { return m_capitulo; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Capitulo", value, value.ToString());
m_isChanged |= (m_capitulo != value); m_capitulo = value;
}
}
/// <summary>
///
/// </summary>
public string Grupocie10
{
get { return m_grupocie10; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Grupocie10", value, value.ToString());
m_isChanged |= (m_grupocie10 != value); m_grupocie10 = value;
}
}
/// <summary>
///
/// </summary>
public string Causa
{
get { return m_causa; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Causa", value, value.ToString());
m_isChanged |= (m_causa != value); m_causa = value;
}
}
/// <summary>
///
/// </summary>
public string Subcausa
{
get { return m_subcausa; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Subcausa", value, value.ToString());
m_isChanged |= (m_subcausa != value); m_subcausa = value;
}
}
/// <summary>
///
/// </summary>
public string Codigo
{
get { return m_codigo; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Codigo", value, value.ToString());
m_isChanged |= (m_codigo != value); m_codigo = value;
}
}
/// <summary>
///
/// </summary>
public string Nombre
{
get { return m_nombre; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for Nombre", value, value.ToString());
m_isChanged |= (m_nombre != value); m_nombre = value;
}
}
/// <summary>
///
/// </summary>
public string DescripCap
{
get { return m_descripcap; }
set
{
if( value != null && value.Length > 255)
throw new ArgumentOutOfRangeException("Invalid value for DescripCap", value, value.ToString());
m_isChanged |= (m_descripcap != value); m_descripcap = value;
}
}
/// <summary>
///
/// </summary>
//public double Modif
//{
// get { return m_modif; }
// set
// {
// m_isChanged |= ( m_modif != value );
// m_modif = value;
// }
//}
/// <summary>
/// Returns whether or not the object has changed it's values.
/// </summary>
public bool IsChanged
{
get { return m_isChanged; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Content.Server.Administration.Logs;
using Content.Server.GameTicking;
using Content.Server.StationEvents.Events;
using Content.Shared;
using Content.Shared.Administration.Logs;
using Content.Shared.CCVar;
using Content.Shared.Database;
using Content.Shared.GameTicking;
using Content.Shared.StationEvents;
using JetBrains.Annotations;
using Robust.Server.Console;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Network;
using Robust.Shared.Random;
using Robust.Shared.Reflection;
using Robust.Shared.Timing;
namespace Content.Server.StationEvents
{
[UsedImplicitly]
// Somewhat based off of TG's implementation of events
public sealed class StationEventSystem : EntitySystem
{
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IServerNetManager _netManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IConGroupController _conGroupController = default!;
[Dependency] private readonly GameTicker _gameTicker = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly AdminLogSystem _adminLog = default!;
public StationEvent? CurrentEvent { get; private set; }
public IReadOnlyCollection<StationEvent> StationEvents => _stationEvents;
private readonly List<StationEvent> _stationEvents = new();
private const float MinimumTimeUntilFirstEvent = 300;
/// <summary>
/// How long until the next check for an event runs
/// </summary>
/// Default value is how long until first event is allowed
private float _timeUntilNextEvent = MinimumTimeUntilFirstEvent;
/// <summary>
/// Whether random events can run
/// </summary>
/// If disabled while an event is running (even if admin run) it will disable it
public bool Enabled
{
get => _enabled;
set
{
if (_enabled == value)
{
return;
}
_enabled = value;
CurrentEvent?.Shutdown();
CurrentEvent = null;
}
}
private bool _enabled = true;
/// <summary>
/// Admins can get a list of all events available to run, regardless of whether their requirements have been met
/// </summary>
/// <returns></returns>
public string GetEventNames()
{
StringBuilder result = new StringBuilder();
foreach (var stationEvent in _stationEvents)
{
result.Append(stationEvent.Name + "\n");
}
return result.ToString();
}
/// <summary>
/// Admins can forcibly run events by passing in the Name
/// </summary>
/// <param name="name">The exact string for Name, without localization</param>
/// <returns></returns>
public string RunEvent(string name)
{
_adminLog.Add(LogType.EventRan, LogImpact.High, $"Event run: {name}");
// Could use a dictionary but it's such a minor thing, eh.
// Wasn't sure on whether to localize this given it's a command
var upperName = name.ToUpperInvariant();
foreach (var stationEvent in _stationEvents)
{
if (stationEvent.Name.ToUpperInvariant() != upperName)
{
continue;
}
CurrentEvent?.Shutdown();
CurrentEvent = stationEvent;
stationEvent.Announce();
return Loc.GetString("station-event-system-run-event", ("eventName", stationEvent.Name));
}
// I had string interpolation but lord it made it hard to read
return Loc.GetString("station-event-system-run-event-no-event-name", ("eventName", name));
}
/// <summary>
/// Randomly run a valid event <b>immediately</b>, ignoring earlieststart
/// </summary>
/// <returns></returns>
public string RunRandomEvent()
{
var randomEvent = PickRandomEvent();
if (randomEvent == null)
{
return Loc.GetString("station-event-system-run-random-event-no-valid-events");
}
CurrentEvent?.Shutdown();
CurrentEvent = randomEvent;
CurrentEvent.Startup();
return Loc.GetString("station-event-system-run-event",("eventName", randomEvent.Name));
}
/// <summary>
/// Randomly picks a valid event.
/// </summary>
public StationEvent? PickRandomEvent()
{
var availableEvents = AvailableEvents(true);
return FindEvent(availableEvents);
}
/// <summary>
/// Admins can stop the currently running event (if applicable) and reset the timer
/// </summary>
/// <returns></returns>
public string StopEvent()
{
string resultText;
if (CurrentEvent == null)
{
resultText = Loc.GetString("station-event-system-stop-event-no-running-event");
}
else
{
resultText = Loc.GetString("station-event-system-stop-event", ("eventName", CurrentEvent.Name));
CurrentEvent.Shutdown();
CurrentEvent = null;
}
ResetTimer();
return resultText;
}
public override void Initialize()
{
base.Initialize();
var reflectionManager = IoCManager.Resolve<IReflectionManager>();
var typeFactory = IoCManager.Resolve<IDynamicTypeFactory>();
foreach (var type in reflectionManager.GetAllChildren(typeof(StationEvent)))
{
if (type.IsAbstract) continue;
var stationEvent = (StationEvent) typeFactory.CreateInstance(type);
IoCManager.InjectDependencies(stationEvent);
_stationEvents.Add(stationEvent);
}
// Can't just check debug / release for a default given mappers need to use release mode
// As such we'll always pause it by default.
_configurationManager.OnValueChanged(CCVars.EventsEnabled, value => Enabled = value, true);
_netManager.RegisterNetMessage<MsgRequestStationEvents>(RxRequest);
_netManager.RegisterNetMessage<MsgStationEvents>();
SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset);
}
private void RxRequest(MsgRequestStationEvents msg)
{
if (_playerManager.TryGetSessionByChannel(msg.MsgChannel, out var player))
SendEvents(player);
}
private void SendEvents(IPlayerSession player)
{
if (!_conGroupController.CanCommand(player, "events"))
return;
var newMsg = _netManager.CreateNetMessage<MsgStationEvents>();
newMsg.Events = StationEvents.Select(e => e.Name).ToArray();
_netManager.ServerSendMessage(newMsg, player.ConnectedClient);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!Enabled && CurrentEvent == null)
{
return;
}
// Stop events from happening in lobby and force active event to end if the round ends
if (Get<GameTicker>().RunLevel != GameRunLevel.InRound)
{
if (CurrentEvent != null)
{
Enabled = false;
}
return;
}
// Keep running the current event
if (CurrentEvent != null)
{
CurrentEvent.Update(frameTime);
// Shutdown the event and set the timer for the next event
if (!CurrentEvent.Running)
{
CurrentEvent.Shutdown();
CurrentEvent = null;
ResetTimer();
}
return;
}
// Make sure we only count down when no event is running.
if (_timeUntilNextEvent > 0 && CurrentEvent == null)
{
_timeUntilNextEvent -= frameTime;
return;
}
// No point hammering this trying to find events if none are available
var stationEvent = FindEvent(AvailableEvents());
if (stationEvent == null)
{
ResetTimer();
}
else
{
CurrentEvent = stationEvent;
CurrentEvent.Announce();
}
}
/// <summary>
/// Reset the event timer once the event is done.
/// </summary>
private void ResetTimer()
{
// 5 - 15 minutes. TG does 3-10 but that's pretty frequent
_timeUntilNextEvent = _random.Next(300, 900);
}
/// <summary>
/// Pick a random event from the available events at this time, also considering their weightings.
/// </summary>
/// <returns></returns>
private StationEvent? FindEvent(List<StationEvent> availableEvents)
{
if (availableEvents.Count == 0)
{
return null;
}
var sumOfWeights = 0;
foreach (var stationEvent in availableEvents)
{
sumOfWeights += (int) stationEvent.Weight;
}
sumOfWeights = _random.Next(sumOfWeights);
foreach (var stationEvent in availableEvents)
{
sumOfWeights -= (int) stationEvent.Weight;
if (sumOfWeights <= 0)
{
return stationEvent;
}
}
return null;
}
/// <summary>
/// Gets the events that have met their player count, time-until start, etc.
/// </summary>
/// <param name="ignoreEarliestStart"></param>
/// <returns></returns>
private List<StationEvent> AvailableEvents(bool ignoreEarliestStart = false)
{
TimeSpan currentTime;
var playerCount = _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
if (!ignoreEarliestStart)
{
currentTime = _gameTicker.RoundDuration();
}
else
{
currentTime = TimeSpan.Zero;
}
var result = new List<StationEvent>();
foreach (var stationEvent in _stationEvents)
{
if (CanRun(stationEvent, playerCount, currentTime))
{
result.Add(stationEvent);
}
}
return result;
}
private bool CanRun(StationEvent stationEvent, int playerCount, TimeSpan currentTime)
{
if (stationEvent.MaxOccurrences.HasValue && stationEvent.Occurrences >= stationEvent.MaxOccurrences.Value)
{
return false;
}
if (playerCount < stationEvent.MinimumPlayers)
{
return false;
}
if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
{
return false;
}
return true;
}
public override void Shutdown()
{
CurrentEvent?.Shutdown();
base.Shutdown();
}
public void Reset(RoundRestartCleanupEvent ev)
{
if (CurrentEvent?.Running == true)
{
CurrentEvent.Shutdown();
CurrentEvent = null;
}
foreach (var stationEvent in _stationEvents)
{
stationEvent.Occurrences = 0;
}
_timeUntilNextEvent = MinimumTimeUntilFirstEvent;
}
}
}
| |
using Api.ApplicationServices;
using Api.Data;
using Api.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Linq;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Mvc;
using Api.ViewModels;
using Api.Models;
namespace tests.Unit
{
[TestClass]
public class ProductControllerTests
{
[TestMethod]
public async Task Given_A_Product_Without_Price_When_Creating_Product_Then_Return_BadRequest()
{
var productDataMock = new Mock<IProductContext>();
//productDataMock.Setup(x => x.GetAllWithHistory()).ReturnsAsync(DummiesProducts);
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "Teste", Price = 0});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Product_With_Empty_Name_When_Creating_Product_Then_Return_BadRequest()
{
var productDataMock = new Mock<IProductContext>();
//productDataMock.Setup(x => x.GetAllWithHistory()).ReturnsAsync(DummiesProducts);
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "", Price = 10});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Product_Already_Exists_When_Creating_Product_Then_Return_BadRequest()
{
var dummieProduct = new Product("Teste", 2);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste")).ReturnsAsync(dummieProduct);
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "Teste", Price = 10});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Creating_Product_Then_Return_Created()
{
var productDataMock = new Mock<IProductContext>();
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "Teste", Price = 10}) as ObjectResult;
Assert.AreEqual(201, result.StatusCode);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Creating_Product_Then_Call_Add_ProductRepo()
{
var productDataMock = new Mock<IProductContext>();
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "Teste", Price = 10});
productDataMock.Verify(x => x.AddProduct(It.IsAny<Product>()), Times.Once);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Creating_Product_Then_Call_Add_ProductHistoryRepo()
{
var productDataMock = new Mock<IProductContext>();
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Post(new CreateProductVm{Name = "Teste", Price = 10});
productDataMock.Verify(x => x.AddProductHistory(It.IsAny<ProductHistory>()), Times.Once);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Updating_ItsPrice_Then_Return_Ok()
{
var productDummie = new Product("Teste", 2);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
Assert.AreEqual(200, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Updating_ItsPrice_Then_Call_UpdateProductDao()
{
var productDummie = new Product("Teste", 2);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
productDataMock.Verify(x => x.Update(It.IsAny<Product>()), Times.Once);
}
[TestMethod]
public async Task Given_A_Valid_Product_When_Updating_ItsPrice_Then_Call_UpdateProductHistoryDao()
{
var productDummie = new Product("Teste", 2);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
productDataMock.Verify(x => x.UpdateProductHistory(It.IsAny<ProductHistory>()), Times.Once);
}
[TestMethod]
public async Task Given_An_Inexistent_Product_When_Updating_It_Then_Return_BadRequest()
{
var productDataMock = new Mock<IProductContext>();
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Product_When_Updating_It_And_Name_Dont_Change_Then_Call_Update()
{
var productDummie = new Product("Teste new", 3);
var productVm = new UpdateProductVm{OldName = "Teste", NewName = "Teste", Price = 10};
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName(productVm.NewName)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.FindByName(productVm.OldName)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(productVm);
productDataMock.Verify(x => x.Update(It.IsAny<Product>()), Times.Once());
}
[TestMethod]
public async Task Given_A_Product_With_Extra_Spaces_Already_Exists_When_Updating_It_Then_Call_Update_Without_Extra_Spaces()
{
var productDummie = new Product("Teste", 3);
var productVm = new UpdateProductVm{OldName = "Teste", NewName = " Teste ", Price = 10};
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName(productDummie.Name)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.FindByName(productVm.OldName)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(productVm) as ObjectResult;
productDataMock.Verify(x => x.Update(It.Is<Product>(p => p.Name == productVm.OldName)), Times.Once());
}
//Por enquanto somos case sensitive
// [TestMethod]
// public async Task Given_A_Product_With_Different_Case_Already_Exists_When_Updating_It_Then_Call_Update_Without_Diferrent_Case()
// {
// var productDummie = new Product("Teste", 3);
// var productVm = new ProductUpdateVm{OldName = "Teste", NewName = "TestE", Price = 10};
// var productDataMock = new Mock<IProductContext>();
// productDataMock.Setup(x => x.FindByName(productDummie.Name)).ReturnsAsync(productDummie);
// productDataMock.Setup(x => x.FindByName(productVm.OldName)).ReturnsAsync(productDummie);
// productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
// var productService = new ProductApplicationService(productDataMock.Object);
// var sut = new ProductController(productService);
// var result = await sut.Put(productVm) as ObjectResult;
// productDataMock.Verify(x => x.Update(It.Is<Product>(p => p.Name == productVm.OldName)), Times.Once());
// }
[TestMethod]
public async Task Given_A_Product_When_Updating_It_To_A_Name_Already_Existent_Then_Do_Not_CallUpdate()
{
var productDummie = new Product("Teste new", 3);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste new")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
productDataMock.Verify(x => x.GetHistory(It.IsAny<string>()), Times.Never());
productDataMock.Verify(x => x.Update(It.IsAny<Product>()), Times.Never());
}
//Ajustar este teste
[TestMethod]
public async Task Given_A_Product_When_Updating_It_To_A_Name_Already_Existent_With_Trim_Spaces_Then_Do_Not_CallUpdate()
{
var productDummie = new Product("Teste no BD", 3);
var productVm = new UpdateProductVm{OldName = "Teste", NewName = " Teste no BD ", Price = 10};
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName(productDummie.Name)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.FindByName(productVm.OldName)).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(productVm);
productDataMock.Verify(x => x.GetHistory(It.IsAny<string>()), Times.Never());
productDataMock.Verify(x => x.Update(It.IsAny<Product>()), Times.Never());
}
[TestMethod]
public async Task Given_A_Product_When_Updating_It_To_A_Name_Already_Existent_Then_Return_BadRequest()
{
var productDummie = new Product("Teste new", 3);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste new")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste", NewName = "Teste new", Price = 10});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
}
[TestMethod]
public async Task Given_A_Product_When_Updating_It_To_A_WhiteSpaceName_Then_Return_BadRequest()
{
var productDummie = new Product("Teste new", 3);
var productDataMock = new Mock<IProductContext>();
productDataMock.Setup(x => x.FindByName("Teste new")).ReturnsAsync(productDummie);
productDataMock.Setup(x => x.GetHistory(productDummie.Id)).ReturnsAsync(new ProductHistory(productDummie));
var productService = new ProductApplicationService(productDataMock.Object);
var sut = new ProductController(productService);
var result = await sut.Put(new UpdateProductVm{OldName = "Teste new", NewName = " ", Price = 10});
Assert.AreEqual(400, (result as ObjectResult).StatusCode);
productDataMock.Verify(x => x.Update(It.IsAny<Product>()), Times.Never());
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
namespace NUnit.Core
{
using System;
using System.Text;
using System.Collections;
/// <summary>
/// The TestResult class represents
/// the result of a test and is used to
/// communicate results across AppDomains.
/// </summary>
///
[Serializable]
public class TestResult
{
#region Fields
/// <summary>
/// Indicates the result of the test
/// </summary>
private ResultState resultState;
/// <summary>
/// Indicates the location of a failure
/// </summary>
private FailureSite failureSite;
/// <summary>
/// The elapsed time for executing this test
/// </summary>
private double time = 0.0;
/// <summary>
/// The test that this result pertains to
/// </summary>
private readonly TestInfo test;
/// <summary>
/// The stacktrace at the point of failure
/// </summary>
private string stackTrace;
/// <summary>
/// Message giving the reason for failure
/// </summary>
private string message;
/// <summary>
/// List of child results
/// </summary>
private IList results;
/// <summary>
/// Number of asserts executed by this test
/// </summary>
private int assertCount = 0;
#endregion
#region Constructor
/// <summary>
/// Construct a test result given a TestInfo
/// </summary>
/// <param name="test">The test to be used</param>
public TestResult(TestInfo test)
{
this.test = test;
this.message = test.IgnoreReason;
}
/// <summary>
/// Construct a TestResult given an ITest
/// </summary>
/// <param name="test"></param>
public TestResult(ITest test) : this( new TestInfo(test) ) { }
/// <summary>
/// Construct a TestResult given a TestName
/// </summary>
/// <param name="testName">A TestName</param>
public TestResult(TestName testName) : this( new TestInfo( testName ) ) { }
#endregion
#region Properties
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState
{
get { return resultState; }
}
/// <summary>
/// Gets the stage of the test in which a failure
/// or error occured.
/// </summary>
public FailureSite FailureSite
{
get { return failureSite; }
}
/// <summary>
/// Indicates whether the test executed
/// </summary>
public bool Executed
{
get
{
return resultState == ResultState.Success ||
resultState == ResultState.Failure ||
resultState == ResultState.Error ||
resultState == ResultState.Inconclusive;
}
}
/// <summary>
/// Gets the name of the test result
/// </summary>
public virtual string Name
{
get { return test.TestName.Name; }
}
/// <summary>
/// Gets the full name of the test result
/// </summary>
public virtual string FullName
{
get { return test.TestName.FullName; }
}
/// <summary>
/// Gets the test associated with this result
/// </summary>
public ITest Test
{
get { return test; }
}
/// <summary>
/// Indicates whether the test ran successfully
/// </summary>
public virtual bool IsSuccess
{
get { return resultState == ResultState.Success; }
}
/// <summary>
/// Indicates whether the test failed
/// </summary>
public virtual bool IsFailure
{
get { return resultState == ResultState.Failure; }
}
/// <summary>
/// Indicates whether the test had an error (as opposed to a failure)
/// </summary>
public virtual bool IsError
{
get { return resultState == ResultState.Error; }
}
/// <summary>
/// Gets a description associated with the test
/// </summary>
public string Description
{
get { return test.Description; }
}
/// <summary>
/// Gets the elapsed time for running the test
/// </summary>
public double Time
{
get { return time; }
set { time = value; }
}
/// <summary>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message
{
get { return message; }
}
/// <summary>
/// Gets any stacktrace associated with an
/// error or failure.
/// </summary>
public virtual string StackTrace
{
get { return stackTrace; }
set { stackTrace = value; }
}
/// <summary>
/// Gets or sets the count of asserts executed
/// when running the test.
/// </summary>
public int AssertCount
{
get { return assertCount; }
set { assertCount = value; }
}
/// <summary>
/// Return true if this result has any child results
/// </summary>
public bool HasResults
{
get { return results != null && results.Count > 0; }
}
/// <summary>
/// Gets a list of the child results of this TestResult
/// </summary>
public IList Results
{
get { return results; }
}
#endregion
#region Public Methods
/// <summary>
/// Mark the test as succeeding
/// </summary>
public void Success()
{
SetResult( ResultState.Success, null, null );
}
/// <summary>
/// Mark the test as succeeding and set a message
/// </summary>
public void Success( string message )
{
SetResult( ResultState.Success, message, null );
}
/// <summary>
/// Mark the test as ignored.
/// </summary>
/// <param name="reason">The reason the test was not run</param>
public void Ignore(string reason)
{
Ignore( reason, null );
}
/// <summary>
/// Mark the test as ignored.
/// </summary>
/// <param name="ex">The ignore exception that was thrown</param>
public void Ignore( Exception ex )
{
Ignore( ex.Message, BuildStackTrace( ex ) );
}
/// <summary>
/// Mark the test as ignored.
/// </summary>
/// <param name="reason">The reason the test was not run</param>
/// <param name="stackTrace">Stack trace giving the location of the command</param>
public void Ignore(string reason, string stackTrace)
{
SetResult( ResultState.Ignored, reason, stackTrace );
}
/// <summary>
/// Mark the test as skipped.
/// </summary>
/// <param name="reason">The reason the test was not run</param>
public void Skip(string reason)
{
SetResult(ResultState.Skipped, reason, null);
}
/// <summary>
/// Mark the test a not runnable with a reason
/// </summary>
/// <param name="reason">The reason the test is invalid</param>
public void Invalid( string reason )
{
SetResult( ResultState.NotRunnable, reason, null );
}
/// <summary>
/// Mark the test as not runnable due to a builder exception
/// </summary>
/// <param name="ex">The exception thrown by the builder or an addin</param>
public void Invalid(Exception ex)
{
SetResult(ResultState.NotRunnable, BuildMessage( ex ), BuildStackTrace(ex));
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="reason">The reason the test was not run</param>
/// <param name="stackTrace">Stack trace giving the location of the command</param>
/// <param name="failureSite">The location of the failure, if any</param>
public void SetResult(ResultState resultState, string reason, string stackTrace, FailureSite failureSite)
{
if (failureSite == FailureSite.SetUp)
reason = "SetUp : " + reason;
else if (failureSite == FailureSite.TearDown)
{
reason = "TearDown : " + reason;
stackTrace = "--TearDown" + Environment.NewLine + stackTrace;
if (this.message != null)
reason = this.message + Environment.NewLine + reason;
if (this.stackTrace != null)
stackTrace = this.stackTrace + Environment.NewLine + stackTrace;
}
this.resultState = resultState;
this.message = reason;
this.stackTrace = stackTrace;
this.failureSite = failureSite;
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="reason">The reason the test was not run</param>
/// <param name="stackTrace">Stack trace giving the location of the command</param>
public void SetResult(ResultState resultState, string reason, string stackTrace)
{
SetResult(resultState, reason, stackTrace, FailureSite.Test);
}
/// <summary>
/// Set the result of the test.
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="ex">The exception that caused this result</param>
/// <param name="failureSite">The site at which an error or failure occured</param>
public void SetResult(ResultState resultState, Exception ex, FailureSite failureSite)
{
if (resultState == ResultState.Cancelled)
SetResult(resultState, "Test cancelled by user", BuildStackTrace(ex));
else if (resultState == ResultState.Error)
SetResult( resultState, BuildMessage(ex), BuildStackTrace(ex), failureSite);
else
SetResult(resultState, ex.Message, ex.StackTrace, failureSite);
}
/// <summary>
/// Mark the test as a failure due to an
/// assertion having failed.
/// </summary>
/// <param name="message">Message to display</param>
/// <param name="stackTrace">Stack trace giving the location of the failure</param>
public void Failure(string message, string stackTrace)
{
Failure(message, stackTrace, FailureSite.Test);
}
/// <summary>
/// Mark the test as a failure due to an
/// assertion having failed.
/// </summary>
/// <param name="message">Message to display</param>
/// <param name="stackTrace">Stack trace giving the location of the failure</param>
/// <param name="failureSite">The site of the failure</param>
public void Failure(string message, string stackTrace, FailureSite failureSite )
{
SetResult( Core.ResultState.Failure, message, stackTrace );
this.failureSite = failureSite;
}
/// <summary>
/// Marks the result as an error due to an exception thrown
/// by the test.
/// </summary>
/// <param name="exception">The exception that was caught</param>
public void Error(Exception exception)
{
Error(exception, FailureSite.Test);
}
/// <summary>
/// Marks the result as an error due to an exception thrown
/// from the indicated FailureSite.
/// </summary>
/// <param name="exception">The exception that was caught</param>
/// <param name="failureSite">The site from which it was thrown</param>
public void Error(Exception exception, FailureSite failureSite)
{
SetResult(ResultState.Error, exception, failureSite);
//string message = BuildMessage(exception);
//string stackTrace = BuildStackTrace(exception);
//if (failureSite == FailureSite.TearDown)
//{
// message = "TearDown : " + message;
// stackTrace = "--TearDown" + Environment.NewLine + stackTrace;
// if (this.message != null)
// message = this.message + Environment.NewLine + message;
// if (this.stackTrace != null)
// stackTrace = this.stackTrace + Environment.NewLine + stackTrace;
//}
//SetResult( ResultState.Error, message, stackTrace );
//this.failureSite = failureSite;
}
/// <summary>
/// Add a child result
/// </summary>
/// <param name="result">The child result to be added</param>
public void AddResult(TestResult result)
{
if ( results == null )
results = new ArrayList();
this.results.Add(result);
switch (result.ResultState)
{
case ResultState.Failure:
case ResultState.Error:
case ResultState.NotRunnable:
if (!this.IsFailure && !this.IsError && this.ResultState != ResultState.NotRunnable)
this.Failure("One or more child tests had errors", null, FailureSite.Child);
break;
case ResultState.Success:
if (this.ResultState == ResultState.Inconclusive)
this.Success();
break;
// Removed this case due to bug #928018
//case ResultState.Ignored:
// if (this.ResultState == ResultState.Inconclusive || ResultState == ResultState.Success)
// this.SetResult(ResultState.Ignored, "One or more child tests were ignored", null, FailureSite.Child);
// break;
case ResultState.Cancelled:
this.SetResult(ResultState.Cancelled, result.Message, null, FailureSite.Child);
break;
}
}
#endregion
#region Exception Helpers
private static string BuildMessage(Exception exception)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "{0} : {1}", exception.GetType().ToString(), exception.Message );
Exception inner = exception.InnerException;
while( inner != null )
{
sb.Append( Environment.NewLine );
sb.AppendFormat( " ----> {0} : {1}", inner.GetType().ToString(), inner.Message );
inner = inner.InnerException;
}
return sb.ToString();
}
private static string BuildStackTrace(Exception exception)
{
StringBuilder sb = new StringBuilder( GetStackTrace( exception ) );
Exception inner = exception.InnerException;
while( inner != null )
{
sb.Append( Environment.NewLine );
sb.Append( "--" );
sb.Append( inner.GetType().Name );
sb.Append( Environment.NewLine );
sb.Append( GetStackTrace( inner ) );
inner = inner.InnerException;
}
return sb.ToString();
}
private static string GetStackTrace(Exception exception)
{
try
{
return exception.StackTrace;
}
catch( Exception )
{
return "No stack trace available";
}
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System.IO;
using System.Runtime;
using System.Security;
using System.Text;
public interface IXmlTextWriterInitializer
{
void SetOutput(Stream stream, Encoding encoding, bool ownsStream);
}
class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer
{
XmlUTF8NodeWriter writer;
//Supports FastAsync APIs
internal override bool FastAsync
{
get
{
return true;
}
}
public void SetOutput(Stream stream, Encoding encoding, bool ownsStream)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
if (encoding == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
if (encoding.WebName != Encoding.UTF8.WebName)
{
stream = new EncodingStreamWrapper(stream, encoding, true);
}
if (writer == null)
{
writer = new XmlUTF8NodeWriter();
}
writer.SetOutput(stream, ownsStream, encoding);
SetOutput(writer);
}
public override bool CanFragment
{
get
{
// Fragmenting only works for utf8
return writer.Encoding == null;
}
}
protected override XmlSigningNodeWriter CreateSigningNodeWriter()
{
return new XmlSigningNodeWriter(true);
}
}
class XmlUTF8NodeWriter : XmlStreamNodeWriter
{
byte[] entityChars;
bool[] isEscapedAttributeChar;
bool[] isEscapedElementChar;
bool inAttribute;
const int bufferLength = 512;
const int maxEntityLength = 32;
const int maxBytesPerChar = 3;
Encoding encoding;
char[] chars;
InternalWriteBase64TextAsyncWriter internalWriteBase64TextAsyncWriter;
static readonly byte[] startDecl =
{
(byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ',
(byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ',
(byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"',
};
static readonly byte[] endDecl =
{
(byte)'"', (byte)'?', (byte)'>'
};
static readonly byte[] utf8Decl =
{
(byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ',
(byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ',
(byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8', (byte)'"',
(byte)'?', (byte)'>'
};
static readonly byte[] digits =
{
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'
};
static readonly bool[] defaultIsEscapedAttributeChar = new bool[]
{
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, // '"', '&'
false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>'
};
static readonly bool[] defaultIsEscapedElementChar = new bool[]
{
true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, // All but 0x09, 0x0A
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, // '&'
false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>'
};
public XmlUTF8NodeWriter()
: this(defaultIsEscapedAttributeChar, defaultIsEscapedElementChar)
{
}
public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar)
{
this.isEscapedAttributeChar = isEscapedAttributeChar;
this.isEscapedElementChar = isEscapedElementChar;
this.inAttribute = false;
}
new public void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
Encoding utf8Encoding = null;
if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage)
{
utf8Encoding = encoding;
encoding = null;
}
base.SetOutput(stream, ownsStream, utf8Encoding);
this.encoding = encoding;
this.inAttribute = false;
}
public Encoding Encoding
{
get
{
return encoding;
}
}
byte[] GetCharEntityBuffer()
{
if (entityChars == null)
{
entityChars = new byte[maxEntityLength];
}
return entityChars;
}
char[] GetCharBuffer(int charCount)
{
if (charCount >= 256)
return new char[charCount];
if (chars == null || chars.Length < charCount)
chars = new char[charCount];
return chars;
}
public override void WriteDeclaration()
{
if (encoding == null)
{
WriteUTF8Chars(utf8Decl, 0, utf8Decl.Length);
}
else
{
WriteUTF8Chars(startDecl, 0, startDecl.Length);
if (encoding.WebName == Encoding.BigEndianUnicode.WebName)
WriteUTF8Chars("utf-16BE");
else
WriteUTF8Chars(encoding.WebName);
WriteUTF8Chars(endDecl, 0, endDecl.Length);
}
}
public override void WriteCData(string text)
{
byte[] buffer;
int offset;
buffer = GetBuffer(9, out offset);
buffer[offset + 0] = (byte)'<';
buffer[offset + 1] = (byte)'!';
buffer[offset + 2] = (byte)'[';
buffer[offset + 3] = (byte)'C';
buffer[offset + 4] = (byte)'D';
buffer[offset + 5] = (byte)'A';
buffer[offset + 6] = (byte)'T';
buffer[offset + 7] = (byte)'A';
buffer[offset + 8] = (byte)'[';
Advance(9);
WriteUTF8Chars(text);
buffer = GetBuffer(3, out offset);
buffer[offset + 0] = (byte)']';
buffer[offset + 1] = (byte)']';
buffer[offset + 2] = (byte)'>';
Advance(3);
}
void WriteStartComment()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'<';
buffer[offset + 1] = (byte)'!';
buffer[offset + 2] = (byte)'-';
buffer[offset + 3] = (byte)'-';
Advance(4);
}
void WriteEndComment()
{
int offset;
byte[] buffer = GetBuffer(3, out offset);
buffer[offset + 0] = (byte)'-';
buffer[offset + 1] = (byte)'-';
buffer[offset + 2] = (byte)'>';
Advance(3);
}
public override void WriteComment(string text)
{
WriteStartComment();
WriteUTF8Chars(text);
WriteEndComment();
}
public override void WriteStartElement(string prefix, string localName)
{
WriteByte('<');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
}
public override void WriteStartElement(string prefix, XmlDictionaryString localName)
{
WriteStartElement(prefix, localName.Value);
}
public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteByte('<');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
}
public override void WriteEndStartElement(bool isEmpty)
{
if (!isEmpty)
{
WriteByte('>');
}
else
{
WriteBytes('/', '>');
}
}
public override void WriteEndElement(string prefix, string localName)
{
WriteBytes('<', '/');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
WriteByte('>');
}
public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteBytes('<', '/');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
WriteByte('>');
}
void WriteStartXmlnsAttribute()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)' ';
buffer[offset + 1] = (byte)'x';
buffer[offset + 2] = (byte)'m';
buffer[offset + 3] = (byte)'l';
buffer[offset + 4] = (byte)'n';
buffer[offset + 5] = (byte)'s';
Advance(6);
inAttribute = true;
}
public override void WriteXmlnsAttribute(string prefix, string ns)
{
WriteStartXmlnsAttribute();
if (prefix.Length != 0)
{
WriteByte(':');
WritePrefix(prefix);
}
WriteBytes('=', '"');
WriteEscapedText(ns);
WriteEndAttribute();
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
WriteXmlnsAttribute(prefix, ns.Value);
}
public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength)
{
WriteStartXmlnsAttribute();
if (prefixLength != 0)
{
WriteByte(':');
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
}
WriteBytes('=', '"');
WriteEscapedText(nsBuffer, nsOffset, nsLength);
WriteEndAttribute();
}
public override void WriteStartAttribute(string prefix, string localName)
{
WriteByte(' ');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
WriteBytes('=', '"');
inAttribute = true;
}
public override void WriteStartAttribute(string prefix, XmlDictionaryString localName)
{
WriteStartAttribute(prefix, localName.Value);
}
public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteByte(' ');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
WriteBytes('=', '"');
inAttribute = true;
}
public override void WriteEndAttribute()
{
WriteByte('"');
inAttribute = false;
}
void WritePrefix(string prefix)
{
if (prefix.Length == 1)
{
WriteUTF8Char(prefix[0]);
}
else
{
WriteUTF8Chars(prefix);
}
}
void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength)
{
if (prefixLength == 1)
{
WriteUTF8Char((char)prefixBuffer[prefixOffset]);
}
else
{
WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength);
}
}
void WriteLocalName(string localName)
{
WriteUTF8Chars(localName);
}
void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength);
}
public override void WriteEscapedText(XmlDictionaryString s)
{
WriteEscapedText(s.Value);
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public override void WriteEscapedText(string s)
{
int count = s.Length;
if (count > 0)
{
fixed (char* chars = s)
{
UnsafeWriteEscapedText(chars, count);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public override void WriteEscapedText(char[] s, int offset, int count)
{
if (count > 0)
{
fixed (char* chars = &s[offset])
{
UnsafeWriteEscapedText(chars, count);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe void UnsafeWriteEscapedText(char* chars, int count)
{
bool[] isEscapedChar = (inAttribute ? isEscapedAttributeChar : isEscapedElementChar);
int isEscapedCharLength = isEscapedChar.Length;
int i = 0;
for (int j = 0; j < count; j++)
{
char ch = chars[j];
if (ch < isEscapedCharLength && isEscapedChar[ch] || ch >= 0xFFFE)
{
UnsafeWriteUTF8Chars(chars + i, j - i);
WriteCharEntity(ch);
i = j + 1;
}
}
UnsafeWriteUTF8Chars(chars + i, count - i);
}
public override void WriteEscapedText(byte[] chars, int offset, int count)
{
bool[] isEscapedChar = (inAttribute ? isEscapedAttributeChar : isEscapedElementChar);
int isEscapedCharLength = isEscapedChar.Length;
int i = 0;
for (int j = 0; j < count; j++)
{
byte ch = chars[offset + j];
if (ch < isEscapedCharLength && isEscapedChar[ch])
{
WriteUTF8Chars(chars, offset + i, j - i);
WriteCharEntity(ch);
i = j + 1;
}
else if (ch == 239 && offset + j + 2 < count)
{
// 0xFFFE and 0xFFFF must be written as char entities
// UTF8(239, 191, 190) = (char) 0xFFFE
// UTF8(239, 191, 191) = (char) 0xFFFF
byte ch2 = chars[offset + j + 1];
byte ch3 = chars[offset + j + 2];
if (ch2 == 191 && (ch3 == 190 || ch3 == 191))
{
WriteUTF8Chars(chars, offset + i, j - i);
WriteCharEntity(ch3 == 190 ? (char)0xFFFE : (char)0xFFFF);
i = j + 3;
}
}
}
WriteUTF8Chars(chars, offset + i, count - i);
}
public void WriteText(int ch)
{
WriteUTF8Char(ch);
}
public override void WriteText(byte[] chars, int offset, int count)
{
WriteUTF8Chars(chars, offset, count);
}
[SecuritySafeCritical]
unsafe public override void WriteText(char[] chars, int offset, int count)
{
if (count > 0)
{
fixed (char* pch = &chars[offset])
{
UnsafeWriteUTF8Chars(pch, count);
}
}
}
public override void WriteText(string value)
{
WriteUTF8Chars(value);
}
public override void WriteText(XmlDictionaryString value)
{
WriteUTF8Chars(value.Value);
}
public void WriteLessThanCharEntity()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'l';
buffer[offset + 2] = (byte)'t';
buffer[offset + 3] = (byte)';';
Advance(4);
}
public void WriteGreaterThanCharEntity()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'g';
buffer[offset + 2] = (byte)'t';
buffer[offset + 3] = (byte)';';
Advance(4);
}
public void WriteAmpersandCharEntity()
{
int offset;
byte[] buffer = GetBuffer(5, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'m';
buffer[offset + 3] = (byte)'p';
buffer[offset + 4] = (byte)';';
Advance(5);
}
public void WriteApostropheCharEntity()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'p';
buffer[offset + 3] = (byte)'o';
buffer[offset + 4] = (byte)'s';
buffer[offset + 5] = (byte)';';
Advance(6);
}
public void WriteQuoteCharEntity()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'q';
buffer[offset + 2] = (byte)'u';
buffer[offset + 3] = (byte)'o';
buffer[offset + 4] = (byte)'t';
buffer[offset + 5] = (byte)';';
Advance(6);
}
void WriteHexCharEntity(int ch)
{
byte[] chars = GetCharEntityBuffer();
int offset = maxEntityLength;
chars[--offset] = (byte)';';
offset -= ToBase16(chars, offset, (uint)ch);
chars[--offset] = (byte)'x';
chars[--offset] = (byte)'#';
chars[--offset] = (byte)'&';
WriteUTF8Chars(chars, offset, maxEntityLength - offset);
}
public override void WriteCharEntity(int ch)
{
switch (ch)
{
case '<':
WriteLessThanCharEntity();
break;
case '>':
WriteGreaterThanCharEntity();
break;
case '&':
WriteAmpersandCharEntity();
break;
case '\'':
WriteApostropheCharEntity();
break;
case '"':
WriteQuoteCharEntity();
break;
default:
WriteHexCharEntity(ch);
break;
}
}
int ToBase16(byte[] chars, int offset, uint value)
{
int count = 0;
do
{
count++;
chars[--offset] = digits[(int)(value & 0x0F)];
value /= 16;
}
while (value != 0);
return count;
}
public override void WriteBoolText(bool value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxBoolChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDecimalText(decimal value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDecimalChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDoubleText(double value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDoubleChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteFloatText(float value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxFloatChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDateTimeText(DateTime value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDateTimeChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteUniqueIdText(UniqueId value)
{
if (value.IsGuid)
{
int charCount = value.CharArrayLength;
char[] chars = GetCharBuffer(charCount);
value.ToCharArray(chars, 0);
WriteText(chars, 0, charCount);
}
else
{
WriteEscapedText(value.ToString());
}
}
public override void WriteInt32Text(int value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxInt32Chars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteInt64Text(long value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxInt64Chars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteUInt64Text(ulong value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxUInt64Chars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteGuidText(Guid value)
{
WriteText(value.ToString());
}
public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
{
if (trailByteCount > 0)
{
InternalWriteBase64Text(trailBytes, 0, trailByteCount);
}
InternalWriteBase64Text(buffer, offset, count);
}
void InternalWriteBase64Text(byte[] buffer, int offset, int count)
{
Base64Encoding encoding = XmlConverter.Base64Encoding;
while (count >= 3)
{
int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3);
int charCount = byteCount / 3 * 4;
int charOffset;
byte[] chars = GetBuffer(charCount, out charOffset);
Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset));
offset += byteCount;
count -= byteCount;
}
if (count > 0)
{
int charOffset;
byte[] chars = GetBuffer(4, out charOffset);
Advance(encoding.GetChars(buffer, offset, count, chars, charOffset));
}
}
internal override AsyncCompletionResult WriteBase64TextAsync(AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> xmlNodeWriterState)
{
if (internalWriteBase64TextAsyncWriter == null)
{
internalWriteBase64TextAsyncWriter = new InternalWriteBase64TextAsyncWriter(this);
}
return this.internalWriteBase64TextAsyncWriter.StartAsync(xmlNodeWriterState);
}
class InternalWriteBase64TextAsyncWriter
{
AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> nodeState;
AsyncEventArgs<XmlWriteBase64AsyncArguments> writerState;
XmlWriteBase64AsyncArguments writerArgs;
XmlUTF8NodeWriter writer;
GetBufferAsyncEventArgs getBufferState;
GetBufferArgs getBufferArgs;
static AsyncEventArgsCallback onTrailByteComplete = new AsyncEventArgsCallback(OnTrailBytesComplete);
static AsyncEventArgsCallback onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete);
static AsyncEventArgsCallback onGetBufferComplete = new AsyncEventArgsCallback(OnGetBufferComplete);
public InternalWriteBase64TextAsyncWriter(XmlUTF8NodeWriter writer)
{
this.writer = writer;
this.writerState = new AsyncEventArgs<XmlWriteBase64AsyncArguments>();
this.writerArgs = new XmlWriteBase64AsyncArguments();
}
internal AsyncCompletionResult StartAsync(AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> xmlNodeWriterState)
{
Fx.Assert(xmlNodeWriterState != null, "xmlNodeWriterState cannot be null.");
Fx.Assert(this.nodeState == null, "nodeState is not null.");
this.nodeState = xmlNodeWriterState;
XmlNodeWriterWriteBase64TextArgs nodeWriterArgs = xmlNodeWriterState.Arguments;
if (nodeWriterArgs.TrailCount > 0)
{
this.writerArgs.Buffer = nodeWriterArgs.TrailBuffer;
this.writerArgs.Offset = 0;
this.writerArgs.Count = nodeWriterArgs.TrailCount;
this.writerState.Set(onTrailByteComplete, this.writerArgs, this);
if (this.InternalWriteBase64TextAsync(this.writerState) != AsyncCompletionResult.Completed)
{
return AsyncCompletionResult.Queued;
}
this.writerState.Complete(true);
}
if (this.WriteBufferAsync() == AsyncCompletionResult.Completed)
{
this.nodeState = null;
return AsyncCompletionResult.Completed;
}
return AsyncCompletionResult.Queued;
}
static private void OnTrailBytesComplete(IAsyncEventArgs eventArgs)
{
InternalWriteBase64TextAsyncWriter thisPtr = (InternalWriteBase64TextAsyncWriter)eventArgs.AsyncState;
Exception completionException = null;
bool completeSelf = false;
try
{
if (eventArgs.Exception != null)
{
completionException = eventArgs.Exception;
completeSelf = true;
}
else if (thisPtr.WriteBufferAsync() == AsyncCompletionResult.Completed)
{
completeSelf = true;
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
completionException = exception;
completeSelf = true;
}
if (completeSelf)
{
AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> state = thisPtr.nodeState;
thisPtr.nodeState = null;
state.Complete(false, eventArgs.Exception);
}
}
AsyncCompletionResult WriteBufferAsync()
{
this.writerArgs.Buffer = nodeState.Arguments.Buffer;
this.writerArgs.Offset = nodeState.Arguments.Offset;
this.writerArgs.Count = nodeState.Arguments.Count;
this.writerState.Set(onWriteComplete, this.writerArgs, this);
if (this.InternalWriteBase64TextAsync(this.writerState) == AsyncCompletionResult.Completed)
{
this.writerState.Complete(true);
return AsyncCompletionResult.Completed;
}
return AsyncCompletionResult.Queued;
}
static void OnWriteComplete(IAsyncEventArgs eventArgs)
{
InternalWriteBase64TextAsyncWriter thisPtr = (InternalWriteBase64TextAsyncWriter)eventArgs.AsyncState;
AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> state = thisPtr.nodeState;
thisPtr.nodeState = null;
state.Complete(false, eventArgs.Exception);
}
AsyncCompletionResult InternalWriteBase64TextAsync(AsyncEventArgs<XmlWriteBase64AsyncArguments> writerState)
{
GetBufferAsyncEventArgs bufferState = this.getBufferState;
GetBufferArgs bufferArgs = this.getBufferArgs;
XmlWriteBase64AsyncArguments writerArgs = writerState.Arguments;
if (bufferState == null)
{
// Need to initialize the cached getBufferState
// used to call GetBufferAsync() multiple times.
bufferState = new GetBufferAsyncEventArgs();
bufferArgs = new GetBufferArgs();
this.getBufferState = bufferState;
this.getBufferArgs = bufferArgs;
}
Base64Encoding encoding = XmlConverter.Base64Encoding;
while (writerArgs.Count >= 3)
{
int byteCount = Math.Min(bufferLength / 4 * 3, writerArgs.Count - writerArgs.Count % 3);
int charCount = byteCount / 3 * 4;
bufferArgs.Count = charCount;
bufferState.Set(onGetBufferComplete, bufferArgs, this);
if (writer.GetBufferAsync(bufferState) == AsyncCompletionResult.Completed)
{
GetBufferEventResult getbufferResult = bufferState.Result;
bufferState.Complete(true);
writer.Advance(encoding.GetChars(
writerArgs.Buffer,
writerArgs.Offset,
byteCount,
getbufferResult.Buffer,
getbufferResult.Offset));
writerArgs.Offset += byteCount;
writerArgs.Count -= byteCount;
}
else
{
return AsyncCompletionResult.Queued;
}
}
if (writerArgs.Count > 0)
{
bufferArgs.Count = 4;
bufferState.Set(onGetBufferComplete, bufferArgs, this);
if (writer.GetBufferAsync(bufferState) == AsyncCompletionResult.Completed)
{
GetBufferEventResult getbufferResult = bufferState.Result;
bufferState.Complete(true);
writer.Advance(encoding.GetChars(
writerArgs.Buffer,
writerArgs.Offset,
writerArgs.Count,
getbufferResult.Buffer,
getbufferResult.Offset));
}
else
{
return AsyncCompletionResult.Queued;
}
}
return AsyncCompletionResult.Completed;
}
static void OnGetBufferComplete(IAsyncEventArgs state)
{
GetBufferEventResult result = ((GetBufferAsyncEventArgs)state).Result;
InternalWriteBase64TextAsyncWriter thisPtr = (InternalWriteBase64TextAsyncWriter)state.AsyncState;
XmlWriteBase64AsyncArguments writerArgs = thisPtr.writerState.Arguments;
Exception completionException = null;
bool completeSelf = false;
try
{
if (state.Exception != null)
{
completionException = state.Exception;
completeSelf = true;
}
else
{
byte[] chars = result.Buffer;
int offset = result.Offset;
Base64Encoding encoding = XmlConverter.Base64Encoding;
int byteCount = Math.Min(bufferLength / 4 * 3, writerArgs.Count - writerArgs.Count % 3);
int charCount = byteCount / 3 * 4;
thisPtr.writer.Advance(encoding.GetChars(
writerArgs.Buffer,
writerArgs.Offset,
byteCount,
chars,
offset));
if (byteCount >= 3)
{
writerArgs.Offset += byteCount;
writerArgs.Count -= byteCount;
}
if (thisPtr.InternalWriteBase64TextAsync(thisPtr.writerState) == AsyncCompletionResult.Completed)
{
completeSelf = true;
}
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
completionException = exception;
completeSelf = true;
}
if (completeSelf)
{
thisPtr.writerState.Complete(false, completionException);
}
}
}
public override IAsyncResult BeginWriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return new WriteBase64TextAsyncResult(trailBytes, trailByteCount, buffer, offset, count, this, callback, state);
}
public override void EndWriteBase64Text(IAsyncResult result)
{
WriteBase64TextAsyncResult.End(result);
}
IAsyncResult BeginInternalWriteBase64Text(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return new InternalWriteBase64TextAsyncResult(buffer, offset, count, this, callback, state);
}
void EndInternalWriteBase64Text(IAsyncResult result)
{
InternalWriteBase64TextAsyncResult.End(result);
}
class WriteBase64TextAsyncResult : AsyncResult
{
static AsyncCompletion onTrailBytesComplete = new AsyncCompletion(OnTrailBytesComplete);
static AsyncCompletion onComplete = new AsyncCompletion(OnComplete);
byte[] trailBytes;
int trailByteCount;
byte[] buffer;
int offset;
int count;
XmlUTF8NodeWriter writer;
public WriteBase64TextAsyncResult(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count, XmlUTF8NodeWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.writer = writer;
this.trailBytes = trailBytes;
this.trailByteCount = trailByteCount;
this.buffer = buffer;
this.offset = offset;
this.count = count;
bool completeSelf = HandleWriteTrailBytes(null);
if (completeSelf)
{
this.Complete(true);
}
}
static bool OnTrailBytesComplete(IAsyncResult result)
{
WriteBase64TextAsyncResult thisPtr = (WriteBase64TextAsyncResult)result.AsyncState;
return thisPtr.HandleWriteTrailBytes(result);
}
static bool OnComplete(IAsyncResult result)
{
WriteBase64TextAsyncResult thisPtr = (WriteBase64TextAsyncResult)result.AsyncState;
return thisPtr.HandleWriteBase64Text(result);
}
bool HandleWriteTrailBytes(IAsyncResult result)
{
if (this.trailByteCount > 0)
{
if (result == null)
{
result = writer.BeginInternalWriteBase64Text(this.trailBytes, 0, this.trailByteCount, PrepareAsyncCompletion(onTrailBytesComplete), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
writer.EndInternalWriteBase64Text(result);
}
return HandleWriteBase64Text(null);
}
bool HandleWriteBase64Text(IAsyncResult result)
{
if (result == null)
{
result = writer.BeginInternalWriteBase64Text(this.buffer, this.offset, this.count, PrepareAsyncCompletion(onComplete), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
writer.EndInternalWriteBase64Text(result);
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteBase64TextAsyncResult>(result);
}
}
class InternalWriteBase64TextAsyncResult : AsyncResult
{
byte[] buffer;
int offset;
int count;
Base64Encoding encoding;
XmlUTF8NodeWriter writer;
static AsyncCallback onWriteCharacters = Fx.ThunkCallback(OnWriteCharacters);
static AsyncCompletion onWriteTrailingCharacters = new AsyncCompletion(OnWriteTrailingCharacters);
public InternalWriteBase64TextAsyncResult(byte[] buffer, int offset, int count, XmlUTF8NodeWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.buffer = buffer;
this.offset = offset;
this.count = count;
this.writer = writer;
this.encoding = XmlConverter.Base64Encoding;
bool completeSelf = ContinueWork();
if (completeSelf)
{
this.Complete(true);
}
}
static bool OnWriteTrailingCharacters(IAsyncResult result)
{
InternalWriteBase64TextAsyncResult thisPtr = (InternalWriteBase64TextAsyncResult)result.AsyncState;
return thisPtr.HandleWriteTrailingCharacters(result);
}
bool ContinueWork()
{
while (this.count >= 3)
{
if (HandleWriteCharacters(null))
{
continue;
}
else
{
// needs to jump async
return false;
}
}
if (count > 0)
{
return HandleWriteTrailingCharacters(null);
}
return true;
}
bool HandleWriteCharacters(IAsyncResult result)
{
int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3);
int charCount = byteCount / 3 * 4;
int charOffset;
if (result == null)
{
result = writer.BeginGetBuffer(charCount, onWriteCharacters, this);
if (!result.CompletedSynchronously)
{
return false;
}
}
byte[] chars = writer.EndGetBuffer(result, out charOffset);
writer.Advance(encoding.GetChars(this.buffer, this.offset, byteCount, chars, charOffset));
this.offset += byteCount;
this.count -= byteCount;
return true;
}
bool HandleWriteTrailingCharacters(IAsyncResult result)
{
if (result == null)
{
result = writer.BeginGetBuffer(4, PrepareAsyncCompletion(onWriteTrailingCharacters), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
int charOffset;
byte[] chars = writer.EndGetBuffer(result, out charOffset);
writer.Advance(encoding.GetChars(this.buffer, this.offset, this.count, chars, charOffset));
return true;
}
static void OnWriteCharacters(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
InternalWriteBase64TextAsyncResult thisPtr = (InternalWriteBase64TextAsyncResult)result.AsyncState;
Exception completionException = null;
bool completeSelf = false;
try
{
thisPtr.HandleWriteCharacters(result);
completeSelf = thisPtr.ContinueWork();
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
completeSelf = true;
completionException = ex;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<InternalWriteBase64TextAsyncResult>(result);
}
}
public override void WriteTimeSpanText(TimeSpan value)
{
WriteText(XmlConvert.ToString(value));
}
public override void WriteStartListText()
{
}
public override void WriteListSeparator()
{
WriteByte(' ');
}
public override void WriteEndListText()
{
}
public override void WriteQualifiedName(string prefix, XmlDictionaryString localName)
{
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteText(localName);
}
}
}
| |
/*
* 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.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula;
public interface Accumulator
{
double Accumulate(double x, double y);
}
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public abstract class XYNumericFunction : Fixed2ArgFunction
{
protected static int X = 0;
protected static int Y = 1;
private abstract class ValueArray : ValueVector
{
private int _size;
protected ValueArray(int size)
{
_size = size;
}
public ValueEval GetItem(int index)
{
if (index < 0 || index > _size)
{
throw new ArgumentException("Specified index " + index
+ " is outside range (0.." + (_size - 1) + ")");
}
return GetItemInternal(index);
}
protected abstract ValueEval GetItemInternal(int index);
public int Size
{
get
{
return _size;
}
}
}
private class SingleCellValueArray : ValueArray
{
private ValueEval _value;
public SingleCellValueArray(ValueEval value)
: base(1)
{
_value = value;
}
protected override ValueEval GetItemInternal(int index)
{
return _value;
}
}
private class RefValueArray : ValueArray
{
private RefEval _ref;
private int _width;
public RefValueArray(RefEval ref1)
: base(ref1.NumberOfSheets)
{
_ref = ref1;
_width = ref1.NumberOfSheets;
}
protected override ValueEval GetItemInternal(int index)
{
int sIx = (index % _width) + _ref.FirstSheetIndex;
return _ref.GetInnerValueEval(sIx);
}
}
private class AreaValueArray : ValueArray
{
private TwoDEval _ae;
private int _width;
public AreaValueArray(TwoDEval ae)
: base(ae.Width * ae.Height)
{
_ae = ae;
_width = ae.Width;
}
protected override ValueEval GetItemInternal(int index)
{
int rowIx = index / _width;
int colIx = index % _width;
return _ae.GetValue(rowIx, colIx);
}
}
protected class DoubleArrayPair
{
private double[] _xArray;
private double[] _yArray;
public DoubleArrayPair(double[] xArray, double[] yArray)
{
_xArray = xArray;
_yArray = yArray;
}
public double[] GetXArray()
{
return _xArray;
}
public double[] GetYArray()
{
return _yArray;
}
}
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1)
{
double result;
try
{
ValueVector vvX = CreateValueVector(arg0);
ValueVector vvY = CreateValueVector(arg1);
int size = vvX.Size;
if (size == 0 || vvY.Size != size)
{
return ErrorEval.NA;
}
result = EvaluateInternal(vvX, vvY, size);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
if (Double.IsNaN(result) || Double.IsInfinity(result))
{
return ErrorEval.NUM_ERROR;
}
return new NumberEval(result);
}
/**
* Constructs a new instance of the Accumulator used to calculated this function
*/
public abstract Accumulator CreateAccumulator();
private double EvaluateInternal(ValueVector x, ValueVector y, int size)
{
Accumulator acc = CreateAccumulator();
// error handling is as if the x is fully evaluated before y
ErrorEval firstXerr = null;
ErrorEval firstYerr = null;
bool accumlatedSome = false;
double result = 0.0;
for (int i = 0; i < size; i++)
{
ValueEval vx = x.GetItem(i);
ValueEval vy = y.GetItem(i);
if (vx is ErrorEval)
{
if (firstXerr == null)
{
firstXerr = (ErrorEval)vx;
continue;
}
}
if (vy is ErrorEval)
{
if (firstYerr == null)
{
firstYerr = (ErrorEval)vy;
continue;
}
}
// only count pairs if both elements are numbers
if (vx is NumberEval && vy is NumberEval)
{
accumlatedSome = true;
NumberEval nx = (NumberEval)vx;
NumberEval ny = (NumberEval)vy;
result += acc.Accumulate(nx.NumberValue, ny.NumberValue);
}
else
{
// all other combinations of value types are silently ignored
}
}
if (firstXerr != null)
{
throw new EvaluationException(firstXerr);
}
if (firstYerr != null)
{
throw new EvaluationException(firstYerr);
}
if (!accumlatedSome)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return result;
}
private static double[] TrimToSize(double[] arr, int len)
{
double[] tarr = arr;
if (arr.Length > len)
{
tarr = new double[len];
Array.Copy(arr, 0, tarr, 0, len);
}
return tarr;
}
private static bool IsNumberEval(Eval eval)
{
//bool retval = false;
//if (eval is NumberEval)
//{
// retval = true;
//}
//else if (eval is RefEval)
//{
// RefEval re = (RefEval)eval;
// ValueEval ve = re.InnerValueEval;
// retval = (ve is NumberEval);
//}
//return retval;
throw new InvalidOperationException("not found in poi");
}
private static double GetDoubleValue(Eval eval)
{
//double retval = 0;
//if (eval is NumberEval)
//{
// NumberEval ne = (NumberEval)eval;
// retval = ne.NumberValue;
//}
//else if (eval is RefEval)
//{
// RefEval re = (RefEval)eval;
// ValueEval ve = re.InnerValueEval;
// retval = (ve is NumberEval)
// ? ((NumberEval)ve).NumberValue
// : double.NaN;
//}
//else if (eval is ErrorEval)
//{
// retval = double.NaN;
//}
//return retval;
throw new InvalidOperationException("not found in poi");
}
private static ValueVector CreateValueVector(ValueEval arg)
{
if (arg is ErrorEval)
{
throw new EvaluationException((ErrorEval)arg);
}
if (arg is TwoDEval)
{
return new AreaValueArray((TwoDEval)arg);
}
if (arg is RefEval)
{
return new RefValueArray((RefEval)arg);
}
return new SingleCellValueArray(arg);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Mail;
namespace IronAHK.Rusty
{
partial class Core
{
/// <summary>
/// Resolves a host name or IP address.
/// </summary>
/// <param name="name">The host name.</param>
/// <returns>A dictionary with the following key/value pairs:
/// <list type="bullet">
/// <item><term>Host</term>: <description>the host name.</description></item>
/// <item><term>Addresses</term>: <description>the list of IP addresses.</description></item>
/// </list>
/// </returns>
public static Dictionary<string, object> GetHostEntry(string name)
{
var entry = Dns.GetHostEntry(name);
var ips = new string[entry.AddressList.Length];
for (int i = 0; i < ips.Length; i++)
ips[i] = entry.AddressList[0].ToString();
var info = new Dictionary<string, object>();
info.Add("Host", entry.HostName);
info.Add("Addresses", ips);
return info;
}
/// <summary>
/// Sends an email.
/// </summary>
/// <param name="recipients">A list of receivers of the message.</param>
/// <param name="subject">Subject of the message.</param>
/// <param name="message">Message body.</param>
/// <param name="options">A dictionary with any the following optional key/value pairs:
/// <list type="bullet">
/// <item><term>Attachments</term>: <description>a list of file paths to send as attachments.</description></item>
/// <item><term>Bcc</term>: <description>a list of blind carbon copy recipients.</description></item>
/// <item><term>CC</term>: <description>a list of carbon copy recipients.</description></item>
/// <item><term>From</term>: <description>the from address.</description></item>
/// <item><term>ReplyTo</term>: <description>the reply address.</description></item>
/// <item><term>Host</term>: <description>the SMTP client hostname and port.</description></item>
/// <item><term>(Header)</term>: <description>any additional header and corresponding value.</description></item>
/// </list>
/// </param>
/// <remarks><see cref="ErrorLevel"/> is set to <c>1</c> if there was a problem, <c>0</c> otherwise.</remarks>
public static void Mail(object recipients, string subject, string message, IDictionary options = null)
{
ErrorLevel = 1;
var msg = new MailMessage { Subject = subject, Body = message };
msg.From = new MailAddress(string.Concat(Environment.UserName, "@", Environment.UserDomainName));
if (recipients is string)
msg.To.Add(new MailAddress((string)recipients));
else if (recipients is IEnumerable)
{
foreach (var item in (IEnumerable)recipients)
if (!string.IsNullOrEmpty(item as string))
msg.To.Add((string)item);
}
else
return;
var smtpHost = "localhost";
int? smtpPort = null;
if (options == null)
goto send;
#region Options
foreach (var key in options.Keys)
{
var item = key as string;
if (string.IsNullOrEmpty(item))
continue;
string[] value;
if (options[key] is string)
value = new[] { (string)options[key] };
else if (options[key] is string[])
value = (string[])options[key];
else if (options[key] is object[])
{
var block = (object[])options[key];
value = new string[block.Length];
for (int i = 0; i < block.Length; i++)
value[i] = block[i] as string;
}
else
continue;
switch (item.ToLowerInvariant())
{
case Keyword_Attachments:
foreach (var entry in value)
if (File.Exists(entry))
msg.Attachments.Add(new Attachment(entry));
break;
case Keyword_Bcc:
foreach (var entry in value)
msg.Bcc.Add(entry);
break;
case Keyword_CC:
foreach (var entry in value)
msg.CC.Add(entry);
break;
case Keyword_From:
msg.From = new MailAddress(value[0]);
break;
case Keyword_ReplyTo:
msg.ReplyTo = new MailAddress(value[0]);
break;
case Keyword_Host:
{
smtpHost = value[0];
var z = smtpHost.LastIndexOf(Keyword_Port);
if (z != -1)
{
var port = smtpHost.Substring(z + 1);
smtpHost = smtpHost.Substring(0, z);
int n;
if (int.TryParse(port, out n))
smtpPort = n;
}
}
break;
default:
msg.Headers.Add(item, value[0]);
break;
}
}
#endregion
send:
var client = smtpPort == null ? new SmtpClient(smtpHost) : new SmtpClient(smtpHost, (int)smtpPort);
try
{
client.Send(msg);
ErrorLevel = 0;
}
catch (SmtpException)
{
if (Debug)
throw;
}
}
/// <summary>
/// Downloads a resource from the internet to a file.
/// </summary>
/// <param name="url">The URL from which to download data.</param>
/// <param name="filename">The file path to receive the data.
/// Any existing file will be overwritten.</param>
[Obsolete]
public static void URLDownloadToFile(string url, string filename)
{
UriDownload(url, filename);
}
/// <summary>
/// Downloads a resource from the internet.
/// </summary>
/// <param name="address">The URI (or URL) of the resource.</param>
/// <param name="filename">The file path to receive the downloaded data. An existing file will be overwritten.
/// Leave blank to return the data as a string.
/// </param>
/// <returns>The downloaded data if <paramref name="filename"/> is blank, otherwise an empty string.</returns>
public static string UriDownload(string address, string filename = null)
{
ErrorLevel = 0;
var flags = ParseFlags(ref address);
var http = new WebClient();
if (flags.Contains("0"))
http.CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
try
{
if (string.IsNullOrEmpty(filename))
return http.DownloadString(address);
http.DownloadFile(address, filename);
}
catch (WebException)
{
ErrorLevel = 1;
}
return string.Empty;
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
namespace GDToolkit.Storage
{
public class PickyList<T>
{
#region --- Field Variables ---
// Variables
public T[] items;
#endregion // Field Variables
#region --- Constructors ---
public PickyList()
{
items= new T[0];
}
#endregion // Constructors
#region --- Properties ---
// Gets the size of the list
public int size
{
get { return items.Length; }
}
// Gets and sets the item of the given index
public T this[int index]
{
get { return items[index]; }
set { items[index]= value; }
}
#endregion // Properties
#region --- Methods ---
// Gets the array of items from the list
public T[] toArray()
{
return items;
}
// Clears the entire list
public void clear()
{
items= new T[0];
}
// Adds the given item into the list, returns if added or not
public bool add(T item)
{
if(contains(item))
return false;
// Variables
T[] temp= new T[size+1];
for(int i= 0; i< size; i++)
temp[i]= items[i];
temp[size]= item;
items= temp;
return true;
}
// Adds the given array of items into the list, returns how many we cut out
public int addRange(params T[] pmItems)
{
// Variables
int totalMissed= 0;
for(int i= 0; i< pmItems.Length; i++)
{
if(!add(pmItems[i]))
totalMissed++;
}
return totalMissed;
}
// Inserts the given item into the given index of the list, returns if added or not
public bool insert(T item, int index)
{
if(contains(item))
return false;
if(index< 0)
index= 0;
if(index>= size)
return add(item);
// Variables
T[] temp= new T[size+1];
int k= index;
for(int i= 0; i< index; i++)
temp[i]= items[i];
temp[index]= item;
for(int h= index+1; h< temp.Length; h++)
temp[h]= items[k++];
items= temp;
return true;
}
// Removes the given item from the list. Returns if found
public bool remove(T item)
{
return removeAt(getIndexOf(item));
}
// Removes the item from the list given the index
public bool removeAt(int index)
{
if(index< 0 || index>= size)
return false;
// Variables
T[] temp= new T[size-1];
int k= index;
for(int i= 0; i< index; i++)
temp[i]= items[i];
if(k>= size)
k= size-1;
for(int h= index; h< temp.Length; h++)
temp[h]= items[k++];
items= temp;
return true;
}
// Pops out the last item of the list and returns it via out. Returns if found (Safer version)
public bool pop(out T item)
{
if(size== 0)
{
item= default(T);
return false;
}
try
{
item= items[size-1];
return removeAt(size-1);
}
catch
{
item= default(T);
return false;
}
}
// Pops out the last item of the list and returns it. (Less Safe Version)
public T pop()
{
// Variables
T item= items[size-1];
removeAt(size-1);
return item;
}
// Finds if the given item is inside the list
public bool contains(T item)
{
for(int i= 0; i< size; i++)
{
if(items[i].Equals(item))
return true;
}
return false;
}
// Gets the index of the given item
public int getIndexOf(T item)
{
for(int i= 0; i< size; i++)
{
if(items[i].Equals(item))
return i;
}
return -1;
}
// Does a for loop, recalling the given modify event
public void forEach(ModifyEvent<T, int> modEvent)
{
for(int i= 0; i< size; i++)
{
modEvent(ref items[i], i);
}
}
// Modifies the item of the given index
public void modifyItem(int index, ModifyEvent<T> modEvent)
{
if(index< 0 || index>= size)
return;
modEvent(ref items[index]);
}
// Modifies the item of the given index, transfers the index to the event
public void modifyItem(int index, ModifyEvent<T, int> modEvent)
{
if(index< 0 || index>= size)
return;
modEvent(ref items[index], index);
}
#endregion // Methods
}
}
// End of File
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The interface and the implementation of a Cache of objects
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.DataStructures
{
/// <summary>
/// The interface for a cache
/// </summary>
public interface ICache<In, Out>
{
void Add(In index, Out output);
/// <summary>
/// Set/Get an element in the cache.
/// When setting, if the element is there, is replaced, otherwise it is created.
/// When getting, if the element is not there, an exception is thrown.
/// </summary>
Out this[In index]
{
get;
set;
}
/// <summary>
/// Is the <code>index</code> in the cache?
/// </summary>
bool ContainsKey(In index);
bool TryGetValue(In index, out Out value);
}
public abstract class GenericCache
{
#region Static fields
[ThreadStatic]
static public int DEFAULT_CACHE_SIZE;
[ThreadStatic]
protected static int cacheHit;
[ThreadStatic]
protected static int cacheMiss;
[ThreadStatic]
protected static int totalCacheAccesses;
#endregion
/// <summary>
/// Get the usage statistics of this cache
/// </summary>
static public string Statistics
{
get
{
StringBuilder output = new StringBuilder();
output.Append("Overall use of the FIFO cache:" + Environment.NewLine);
output.AppendFormat("Cache accesses : {0}" + Environment.NewLine, totalCacheAccesses);
output.AppendFormat("Cache Hit : {0} ({1:P})" + Environment.NewLine, cacheHit, totalCacheAccesses != 0 ? cacheHit / (double)totalCacheAccesses : 0);
output.AppendFormat("Cache Miss: {0}" + Environment.NewLine, totalCacheAccesses - cacheHit);
return output.ToString();
}
}
}
/// <summary>
/// A cache where the politics for removing elements if a <code>FIFO</code>
/// </summary>
public class FIFOCache<In, Out> : GenericCache, ICache<In, Out>
{
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(elements != null);
Contract.Invariant(fifo != null);
}
#endregion
#region Private state
readonly private Dictionary<In, Out> elements;
readonly private LinkedList<In> fifo;
private int size;
#endregion
#region Constructor
/// <summary>
/// The size of the cache
/// </summary>
/// <param name="size">Must be strictly positive</param>
public FIFOCache(int size)
{
Contract.Requires(size > 0, "The size of the cache must be strictly positive.");
elements = new Dictionary<In, Out>(size);
fifo = new LinkedList<In>();
this.size = size;
}
/// <summary>
/// Construct a cache of default size
/// </summary>
public FIFOCache()
: this(DEFAULT_CACHE_SIZE)
{
}
#endregion
#region ICache<In,Out> Members
/// <summary>
/// Add an element to the cache.
/// If <code>index</code> is in the cache, then <code>this[index] == output</code>
/// </summary>
public void Add(In index, Out output)
{
if (elements.ContainsKey(index))
{
// Contract.Assert(!Object.Equals(this.elements[index], output), "Error: trying to set a different value in the cache for the same input");
return;
}
if (elements.Count < size) // there is still room for a new element in the cache
{
elements[index] = output;
fifo.AddLast(index); // Add at the end of the queue
}
else
{
//^ assert this.fifo.First != null;
In toRemove = fifo.First.Value;
fifo.RemoveFirst(); // Remove the first element of the queue
elements.Remove(toRemove);
this.Add(index, output); // Now there must be space, so we call ourselves recursively
}
}
public bool TryGetValue(In index, out Out value)
{
totalCacheAccesses++;
bool b = elements.TryGetValue(index, out value);
if (b)
{
cacheHit++;
}
return b;
}
/// <summary>
/// Get/Sets elements of the cache
/// </summary>
public Out this[In index]
{
get
{
totalCacheAccesses++;
return elements[index];
}
set
{
totalCacheAccesses++;
this.Add(index, value);
}
}
/// <summary>
/// Is the <code>index</code> in this cache
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool ContainsKey(In index)
{
bool b = elements.ContainsKey(index);
// Updates the statistics
totalCacheAccesses++;
if (b)
cacheHit++;
else
cacheMiss++;
return b;
}
#endregion
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Collections.Generic;
using System.Globalization;
/// <summary>
/// Represents a single SQL statement in SQLite.
/// </summary>
internal sealed class SqliteStatement : IDisposable
{
/// <summary>
/// The underlying SQLite object this statement is bound to
/// </summary>
internal SQLiteBase _sql;
/// <summary>
/// The command text of this SQL statement
/// </summary>
internal string _sqlStatement;
/// <summary>
/// The actual statement pointer
/// </summary>
internal SqliteStatementHandle _sqlite_stmt;
/// <summary>
/// An index from which unnamed parameters begin
/// </summary>
internal int _unnamedParameters;
/// <summary>
/// Names of the parameters as SQLite understands them to be
/// </summary>
internal string[] _paramNames;
/// <summary>
/// Parameters for this statement
/// </summary>
internal SqliteParameter[] _paramValues;
/// <summary>
/// Command this statement belongs to (if any)
/// </summary>
internal SqliteCommand _command;
private string[] _types;
/// <summary>
/// Initializes the statement and attempts to get all information about parameters in the statement
/// </summary>
/// <param name="sqlbase">The base SQLite object</param>
/// <param name="stmt">The statement</param>
/// <param name="strCommand">The command text for this statement</param>
/// <param name="previous">The previous command in a multi-statement command</param>
internal SqliteStatement(SQLiteBase sqlbase, SqliteStatementHandle stmt, string strCommand, SqliteStatement previous)
{
_sql = sqlbase;
_sqlite_stmt = stmt;
_sqlStatement = strCommand;
// Determine parameters for this statement (if any) and prepare space for them.
int nCmdStart = 0;
int n = _sql.Bind_ParamCount(this);
int x;
string s;
if (n > 0)
{
if (previous != null)
nCmdStart = previous._unnamedParameters;
_paramNames = new string[n];
_paramValues = new SqliteParameter[n];
for (x = 0; x < n; x++)
{
s = _sql.Bind_ParamName(this, x + 1);
if (String.IsNullOrEmpty(s))
{
s = String.Format(CultureInfo.InvariantCulture, ";{0}", nCmdStart);
nCmdStart++;
_unnamedParameters++;
}
_paramNames[x] = s;
_paramValues[x] = null;
}
}
}
/// <summary>
/// Called by SqliteParameterCollection, this function determines if the specified parameter name belongs to
/// this statement, and if so, keeps a reference to the parameter so it can be bound later.
/// </summary>
/// <param name="s">The parameter name to map</param>
/// <param name="p">The parameter to assign it</param>
internal bool MapParameter(string s, SqliteParameter p)
{
if (_paramNames == null) return false;
int startAt = 0;
if (s.Length > 0)
{
if (":$@;".IndexOf(s[0]) == -1)
startAt = 1;
}
int x = _paramNames.Length;
for (int n = 0; n < x; n++)
{
if (String.Compare(_paramNames[n], startAt, s, 0, Math.Max(_paramNames[n].Length - startAt, s.Length), true, CultureInfo.InvariantCulture) == 0)
{
_paramValues[n] = p;
return true;
}
}
return false;
}
#region IDisposable Members
/// <summary>
/// Disposes and finalizes the statement
/// </summary>
public void Dispose()
{
if (_sqlite_stmt != null)
{
_sqlite_stmt.Dispose();
}
_sqlite_stmt = null;
_paramNames = null;
_paramValues = null;
_sql = null;
_sqlStatement = null;
}
#endregion
/// <summary>
/// Bind all parameters, making sure the caller didn't miss any
/// </summary>
internal void BindParameters()
{
if (_paramNames == null) return;
int x = _paramNames.Length;
for (int n = 0; n < x; n++)
{
BindParameter(n + 1, _paramValues[n]);
}
}
/// <summary>
/// Perform the bind operation for an individual parameter
/// </summary>
/// <param name="index">The index of the parameter to bind</param>
/// <param name="param">The parameter we're binding</param>
private void BindParameter(int index, SqliteParameter param)
{
if (param == null)
throw new SqliteException((int)SQLiteErrorCode.Error, "Insufficient parameters supplied to the command");
object obj = param.Value;
DbType objType = param.DbType;
if (Convert.IsDBNull(obj) || obj == null)
{
_sql.Bind_Null(this, index);
return;
}
if (objType == DbType.Object)
objType = SqliteConvert.TypeToDbType(obj.GetType());
switch (objType)
{
case DbType.Date:
case DbType.Time:
case DbType.DateTime:
_sql.Bind_DateTime(this, index, Convert.ToDateTime(obj, CultureInfo.CurrentCulture));
break;
case DbType.UInt32:
case DbType.Int64:
case DbType.UInt64:
_sql.Bind_Int64(this, index, Convert.ToInt64(obj, CultureInfo.CurrentCulture));
break;
case DbType.Boolean:
case DbType.Int16:
case DbType.Int32:
case DbType.UInt16:
case DbType.SByte:
case DbType.Byte:
_sql.Bind_Int32(this, index, Convert.ToInt32(obj, CultureInfo.CurrentCulture));
break;
case DbType.Single:
case DbType.Double:
case DbType.Currency:
//case DbType.Decimal: // Dont store decimal as double ... loses precision
_sql.Bind_Double(this, index, Convert.ToDouble(obj, CultureInfo.CurrentCulture));
break;
case DbType.Binary:
_sql.Bind_Blob(this, index, (byte[])obj);
break;
case DbType.Guid:
if (_command.Connection._binaryGuid == true)
_sql.Bind_Blob(this, index, ((Guid)obj).ToByteArray());
else
_sql.Bind_Text(this, index, obj.ToString());
break;
case DbType.Decimal: // Dont store decimal as double ... loses precision
_sql.Bind_Text(this, index, Convert.ToDecimal(obj, CultureInfo.CurrentCulture).ToString(CultureInfo.InvariantCulture));
break;
default:
_sql.Bind_Text(this, index, obj.ToString());
break;
}
}
internal string[] TypeDefinitions
{
get { return _types; }
}
internal void SetTypes(string typedefs)
{
int pos = typedefs.IndexOf("TYPES", 0, StringComparison.OrdinalIgnoreCase);
if (pos == -1) throw new ArgumentOutOfRangeException();
string[] types = typedefs.Substring(pos + 6).Replace(" ", "").Replace(";", "").Replace("\"", "").Replace("[", "").Replace("]", "").Replace("`","").Split(',', '\r', '\n', '\t');
int n;
for (n = 0; n < types.Length; n++)
{
if (String.IsNullOrEmpty(types[n]) == true)
types[n] = null;
}
_types = types;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class RelativisticObject : MonoBehaviour {
//Keep track of our own Mesh Filter
private MeshFilter meshFilter;
//Store our raw vertices in this variable, so that we can refer to them later
private Vector3[] rawVerts;
//Store this object's velocity here.
public Vector3 viw;
//Keep track of Game State so that we can reference it quickly
private GameState state;
//When was this object created? use for moving objects
private float startTime = 0;
//When should we die? again, for moving objects
private float deathTime = 0;
// Get the start time of our object, so that we know where not to draw it
public void SetStartTime()
{
startTime = (float) GameObject.FindGameObjectWithTag("Playermesh").GetComponent<GameState>().TotalTimeWorld;
}
//Set the death time, so that we know at what point to destroy the object in the player's view point.
public void SetDeathTime()
{
deathTime = (float)state.TotalTimeWorld;
}
void Start()
{
//Get the player's GameState, use it later for general information
state = GameObject.FindGameObjectWithTag("Playermesh").GetComponent<GameState>();
checkSpeed();
//Get the meshfilter
meshFilter = GetComponent<MeshFilter>();
//Also get the meshrenderer so that we can give it a unique material
MeshRenderer tempRenderer = GetComponent<MeshRenderer>();
//If we have a MeshRenderer on our object
if (tempRenderer != null)
{
//And if we have a texture on our material
if (tempRenderer.materials[0].mainTexture != null)
{
//So that we can set unique values to every moving object, we have to instantiate a material
//It's the same as our old one, but now it's not connected to every other object with the same material
Material quickSwapMaterial = Instantiate((tempRenderer as Renderer).materials[0]) as Material;
//Then, set the value that we want
//And stick it back into our renderer. We'll do the SetVector thing every frame.
tempRenderer.materials[0] = quickSwapMaterial;
tempRenderer.materials[0].SetFloat("_strtTime", (float)startTime);
tempRenderer.materials[0].SetVector("_strtPos", new Vector4(transform.position.x, transform.position.y, transform.position.z, 0));
}
}
//Get the vertices of our mesh
if (meshFilter != null)
{
rawVerts = meshFilter.mesh.vertices;
}
else
rawVerts = null;
//This code is a hack to ensure that frustrum culling does not take place
//It changes the render bounds so that everything is contained within them
//At high speeds the Lorenz contraction means that some objects not normally in the view frame are actually visible
//If we did frustrum culling, these objects would be ignored (because we cull BEFORE running the shader, which does the lorenz contraction)
Transform camTransform = Camera.main.transform;
float distToCenter = (Camera.main.farClipPlane - Camera.main.nearClipPlane) / 2.0f;
Vector3 center = camTransform.position + camTransform.forward * distToCenter;
float extremeBound = 500000.0f;
meshFilter.sharedMesh.bounds = new Bounds(center, Vector3.one * extremeBound);
}
void Update()
{
//Grab our renderer.
MeshRenderer tempRenderer = GetComponent<MeshRenderer>();
if (meshFilter != null && !state.MovementFrozen)
{
#region meshDensity
//This is where I'm going to change our mesh density.
//I'll take the model, and pass MeshDensity the mesh and unchanged vertices
//If it comes back as having changed something, I'll edit the mesh.
ObjectMeshDensity density = GetComponent<ObjectMeshDensity>();
if (density != null)
{
//Only run MeshDensity if the mesh needs to change, and if it's passed a threshold distance.
if (rawVerts != null && density.change != null)
{
//This checks if we're within our large range, first mesh density circle
//If we're within a distance of 40, split this mesh
if (density.state == false && RecursiveTransform(rawVerts[0], meshFilter.transform).magnitude < 21000)
{
if (density.ReturnVerts(meshFilter.mesh, true))
{
rawVerts = new Vector3[meshFilter.mesh.vertices.Length];
System.Array.Copy(meshFilter.mesh.vertices, rawVerts, meshFilter.mesh.vertices.Length);
}
}
//If the object leaves our wide range, revert mesh to original state
else if (density.state == true && RecursiveTransform(rawVerts[0], meshFilter.transform).magnitude > 21000)
{
if (density.ReturnVerts(meshFilter.mesh, false))
{
rawVerts = new Vector3[meshFilter.mesh.vertices.Length];
System.Array.Copy(meshFilter.mesh.vertices, rawVerts, meshFilter.mesh.vertices.Length);
}
}
}
}
#endregion
//Send our object's v/c (Velocity over the Speed of Light) to the shader
if (tempRenderer != null)
{
Vector3 tempViw = viw / (float)state.SpeedOfLight;
tempRenderer.materials[0].SetVector("_viw", new Vector4(tempViw.x, tempViw.y, tempViw.z, 0));
}
//As long as our object is actually alive, perform these calculations
if (transform!=null && deathTime != 0)
{
//Here I take the angle that the player's velocity vector makes with the z axis
float rotationAroundZ = 57.2957795f * Mathf.Acos(Vector3.Dot(state.rigid.vitesse, Vector3.forward) / state.rigid.vitesse.magnitude);
if (state.rigid.vitesse.sqrMagnitude == 0)
{
rotationAroundZ = 0;
}
//Now we turn that rotation into a quaternion
Quaternion rotateZ = Quaternion.AngleAxis(-rotationAroundZ, Vector3.Cross(state.rigid.vitesse,Vector3.forward));
//******************************************************************
//Place the vertex to be changed in a new Vector3
Vector3 riw = new Vector3(transform.position.x, transform.position.y, transform.position.z);
riw -= state.playerTransform.position;
//And we rotate our point that much to make it as if our magnitude of velocity is in the Z direction
riw = rotateZ * riw;
//Here begins the original code, made by the guys behind the Relativity game
/****************************
* Start Part 6 Bullet 1
*/
//Rotate that velocity!
Vector3 storedViw = rotateZ * viw;
float c = -Vector3.Dot(riw, riw); //first get position squared (position doted with position)
float b = -(2 * Vector3.Dot(riw, storedViw)); //next get position doted with velocity, should be only in the Z direction
float a = (float)state.SpeedOfLightSqrd - Vector3.Dot(storedViw, storedViw);
/****************************
* Start Part 6 Bullet 2
* **************************/
float tisw = (float)(((-b - (Math.Sqrt((b * b) - 4f * a * c))) / (2f * a)));
//If we're past our death time (in the player's view, as seen by tisw)
if (state.TotalTimeWorld + tisw > deathTime)
{
Destroy(this.gameObject);
}
}
//make our rigidbody's velocity viw
if (GetComponent<Rigidbody>()!=null)
{
if (!double.IsNaN((double)state.SqrtOneMinusVSquaredCWDividedByCSquared) && (float)state.SqrtOneMinusVSquaredCWDividedByCSquared != 0)
{
Vector3 tempViw = viw;
//ASK RYAN WHY THESE WERE DIVIDED BY THIS
tempViw.x /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
tempViw.y /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
tempViw.z /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
GetComponent<Rigidbody>().velocity = tempViw;
}
}
}
//If nothing is null, then set the object to standstill, but make sure its rigidbody actually has a velocity.
else if (meshFilter != null && tempRenderer != null && GetComponent<Rigidbody>() != null)
{
GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
public Vector3 RecursiveTransform(Vector3 pt, Transform trans)
{
//Basically, this will transform the point until it has no more parent transforms.
Vector3 pt1 = Vector3.zero;
//If we have a parent transform, run this function again
if (trans.parent != null)
{
pt = RecursiveTransform(pt1, trans.parent);
return pt;
}
else
{
pt1 = trans.TransformPoint(pt);
return pt1;
}
}
//This is a function that just ensures we're slower than our maximum speed. The VIW that Unity sets SHOULD (it's creator-chosen) be smaller than the maximum speed.
private void checkSpeed()
{
if (viw.magnitude > TRR.SPEEDOFLIGHT-.01)
{
viw = viw.normalized * (float)(state.MaxSpeed-.01f);
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
public class Reflect : global::haxe.lang.HxObject {
public Reflect(global::haxe.lang.EmptyObject empty){
unchecked {
#line 48 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
{
}
}
#line default
}
public Reflect(){
unchecked {
#line 48 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
global::Reflect.__hx_ctor__Reflect(this);
}
#line default
}
public static void __hx_ctor__Reflect(global::Reflect __temp_me7){
unchecked {
#line 48 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
{
}
}
#line default
}
public static bool hasField(object o, string field){
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, true, false) != haxe.lang.Runtime.undefined;
return haxe.lang.Runtime.slowHasField(o, field);
}
public static object field(object o, string field){
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, false, false);
return haxe.lang.Runtime.slowGetField(o, field, false);
}
public static void setField(object o, string field, object @value){
if (o is haxe.lang.IHxObject)
((haxe.lang.IHxObject) o).__hx_setField(field, haxe.lang.FieldLookup.hash(field), value, false);
else
haxe.lang.Runtime.slowSetField(o, field, value);
}
public static object getProperty(object o, string field){
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, false, true);
if (haxe.lang.Runtime.slowHasField(o, "get_" + field))
return haxe.lang.Runtime.slowCallField(o, "get_" + field, null);
return haxe.lang.Runtime.slowGetField(o, field, false);
}
public static void setProperty(object o, string field, object @value){
if (o is haxe.lang.IHxObject)
((haxe.lang.IHxObject) o).__hx_setField(field, haxe.lang.FieldLookup.hash(field), value, true);
else if (haxe.lang.Runtime.slowHasField(o, "set_" + field))
haxe.lang.Runtime.slowCallField(o, "set_" + field, new Array<object>(new object[]{value}));
else
haxe.lang.Runtime.slowSetField(o, field, value);
}
public static object callMethod(object o, object func, global::Array args){
return ((haxe.lang.Function) func).__hx_invokeDynamic(args);
}
public static global::Array<object> fields(object o){
if (o is haxe.lang.IHxObject)
{
Array<object> ret = new Array<object>();
((haxe.lang.IHxObject) o).__hx_getFields(ret);
return ret;
} else if (o is System.Type) {
return Type.getClassFields( (System.Type) o);
} else {
return new Array<object>();
}
}
public static bool isFunction(object f){
return f is haxe.lang.Function;
}
public static int compare<T>(T a, T b){
return haxe.lang.Runtime.compare(a, b);
}
public static bool compareMethods(object f1, object f2){
if (f1 == f2)
return true;
if (f1 is haxe.lang.Closure && f2 is haxe.lang.Closure)
{
haxe.lang.Closure f1c = (haxe.lang.Closure) f1;
haxe.lang.Closure f2c = (haxe.lang.Closure) f2;
return haxe.lang.Runtime.refEq(f1c.obj, f2c.obj) && f1c.field.Equals(f2c.field);
}
return false;
}
public static bool isObject(object v){
return v != null && !(v is haxe.lang.Enum || v is haxe.lang.Function || v is System.ValueType);
}
public static bool isEnumValue(object v){
return v != null && (v is haxe.lang.Enum || v is System.Enum);
}
public static bool deleteField(object o, string field){
return (o is haxe.lang.DynamicObject && ((haxe.lang.DynamicObject) o).__hx_deleteField(field, haxe.lang.FieldLookup.hash(field)));
}
public static T copy<T>(T o){
unchecked {
#line 198 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
object o2 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{}), new global::Array<object>(new object[]{}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
{
#line 199 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
int _g = 0;
#line 199 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
global::Array<object> _g1 = global::Reflect.fields(o);
#line 199 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
while (( _g < _g1.length )){
#line 199 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
string f = global::haxe.lang.Runtime.toString(_g1[_g]);
#line 199 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
++ _g;
global::Reflect.setField(o2, f, global::Reflect.field(o, f));
}
}
#line 201 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
return global::haxe.lang.Runtime.genericCast<T>(o2);
}
#line default
}
public static object makeVarArgs(global::haxe.lang.Function f){
unchecked {
#line 207 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
return new global::haxe.lang.VarArgsFunction(((global::haxe.lang.Function) (f) ));
}
#line default
}
public static new object __hx_createEmpty(){
unchecked {
#line 48 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
return new global::Reflect(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr){
unchecked {
#line 48 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\Reflect.hx"
return new global::Reflect();
}
#line default
}
}
| |
using System;
using UnityEngine;
[AddComponentMenu("NGUI/Interaction/Button Color"), ExecuteInEditMode]
public class UIButtonColor : UIWidgetContainer
{
public enum State
{
Normal,
Hover,
Pressed,
Disabled
}
public GameObject tweenTarget;
public Color hover = new Color(1f, 1f, 1f, 1f);
public Color pressed = new Color(1f, 1f, 1f, 1f);
public Color disabledColor = new Color(1f, 1f, 1f, 1f);
public float duration = 0.2f;
protected Color mColor;
protected bool mInitDone;
protected UIWidget mWidget;
protected UIButtonColor.State mState;
public Color defaultColor
{
get
{
if (!this.mInitDone)
{
this.OnInit();
}
return this.mColor;
}
set
{
if (!this.mInitDone)
{
this.OnInit();
}
this.mColor = value;
}
}
public virtual bool isEnabled
{
get
{
return base.enabled;
}
set
{
base.enabled = value;
}
}
private void Awake()
{
if (!this.mInitDone)
{
this.OnInit();
}
}
private void Start()
{
if (!this.isEnabled)
{
this.SetState(UIButtonColor.State.Disabled, true);
}
}
protected virtual void OnInit()
{
this.mInitDone = true;
if (this.tweenTarget == null)
{
this.tweenTarget = base.gameObject;
}
this.mWidget = this.tweenTarget.GetComponent<UIWidget>();
if (this.mWidget != null)
{
this.mColor = this.mWidget.color;
}
else
{
Renderer renderer = this.tweenTarget.renderer;
if (renderer != null)
{
this.mColor = ((!Application.isPlaying) ? renderer.sharedMaterial.color : renderer.material.color);
}
else
{
Light light = this.tweenTarget.light;
if (light != null)
{
this.mColor = light.color;
}
else
{
this.tweenTarget = null;
this.mInitDone = false;
}
}
}
}
protected virtual void OnEnable()
{
if (this.mInitDone)
{
this.OnHover(UICamera.IsHighlighted(base.gameObject));
}
if (UICamera.currentTouch != null)
{
if (UICamera.currentTouch.pressed == base.gameObject)
{
this.OnPress(true);
}
else if (UICamera.currentTouch.current == base.gameObject)
{
this.OnHover(true);
}
}
}
protected virtual void OnDisable()
{
if (this.mInitDone && this.tweenTarget != null)
{
this.SetState(UIButtonColor.State.Normal, true);
TweenColor component = this.tweenTarget.GetComponent<TweenColor>();
if (component != null)
{
component.value = this.mColor;
component.enabled = false;
}
}
}
protected virtual void OnHover(bool isOver)
{
if (this.isEnabled)
{
if (!this.mInitDone)
{
this.OnInit();
}
if (this.tweenTarget != null)
{
this.SetState((!isOver) ? UIButtonColor.State.Normal : UIButtonColor.State.Hover, false);
}
}
}
protected virtual void OnPress(bool isPressed)
{
if (this.isEnabled && UICamera.currentTouch != null)
{
if (!this.mInitDone)
{
this.OnInit();
}
if (this.tweenTarget != null)
{
if (isPressed)
{
this.SetState(UIButtonColor.State.Pressed, false);
}
else if (UICamera.currentTouch.current == base.gameObject)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
{
this.SetState(UIButtonColor.State.Hover, false);
}
else if (UICamera.currentScheme == UICamera.ControlScheme.Mouse && UICamera.hoveredObject == base.gameObject)
{
this.SetState(UIButtonColor.State.Hover, false);
}
else
{
this.SetState(UIButtonColor.State.Normal, false);
}
}
else
{
this.SetState(UIButtonColor.State.Normal, false);
}
}
}
}
protected virtual void OnDragOver()
{
if (this.isEnabled)
{
if (!this.mInitDone)
{
this.OnInit();
}
if (this.tweenTarget != null)
{
this.SetState(UIButtonColor.State.Pressed, false);
}
}
}
protected virtual void OnDragOut()
{
if (this.isEnabled)
{
if (!this.mInitDone)
{
this.OnInit();
}
if (this.tweenTarget != null)
{
this.SetState(UIButtonColor.State.Normal, false);
}
}
}
protected virtual void OnSelect(bool isSelected)
{
if (this.isEnabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller) && this.tweenTarget != null)
{
this.OnHover(isSelected);
}
}
protected virtual void SetState(UIButtonColor.State state, bool instant)
{
if (!this.mInitDone)
{
this.mInitDone = true;
this.OnInit();
}
if (this.mState != state)
{
this.mState = state;
TweenColor tweenColor;
switch (this.mState)
{
case UIButtonColor.State.Hover:
tweenColor = TweenColor.Begin(this.tweenTarget, this.duration, this.hover);
break;
case UIButtonColor.State.Pressed:
tweenColor = TweenColor.Begin(this.tweenTarget, this.duration, this.pressed);
break;
case UIButtonColor.State.Disabled:
tweenColor = TweenColor.Begin(this.tweenTarget, this.duration, this.disabledColor);
break;
default:
tweenColor = TweenColor.Begin(this.tweenTarget, this.duration, this.mColor);
break;
}
if (instant && tweenColor != null)
{
tweenColor.value = tweenColor.to;
tweenColor.enabled = false;
}
}
}
private void OnDestroy()
{
this.tweenTarget = null;
}
}
| |
namespace MultiSelectTreeView.Test.Model.Helper
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Class for Keyboard use
/// </summary>
public static class Mouse
{
#region Constants
const int SM_SWAPBUTTON = 23;
const int SM_XVIRTUALSCREEN = 76;
const int SM_YVIRTUALSCREEN = 77;
const int SM_CXVIRTUALSCREEN = 78;
const int SM_CYVIRTUALSCREEN = 79;
const int MOUSEEVENTF_VIRTUALDESK = 0x4000;
#endregion
#region Specific tree methods
internal static void ExpandCollapseClick(Element element)
{
bool oldExpandState = element.IsExpanded;
AutomationElement toggleButton = element.Ae.FindDescendantByAutomationId(ControlType.Button, "Expander");
try
{
Click(toggleButton.GetClickablePoint());
}
catch
{
}
SleepAfter();
if (oldExpandState == element.IsExpanded)
throw new InvalidOperationException("Changing expand state did not work");
}
internal static void Click(Element element)
{
Click(element.Ae);
SleepAfter();
}
internal static void ShiftClick(Element element)
{
Keyboard.HoldShift();
Click(element.Ae);
SleepBetween();
Keyboard.ReleaseShift();
}
internal static void CtrlClick(Element element)
{
Keyboard.HoldCtrl();
Click(element.Ae);
SleepBetween();
Keyboard.ReleaseCtrl();
}
private static void SleepAfter()
{
Thread.Sleep(500);
}
private static void SleepBetween()
{
Thread.Sleep(10);
}
#endregion
#region Private methods
/// <summary>
/// Inject pointer input into the system
/// </summary>
/// <param name="x">x coordinate of pointer, if Move flag specified</param>
/// <param name="y">y coordinate of pointer, if Move flag specified</param>
/// <param name="data">wheel movement, or mouse X button, depending on flags</param>
/// <param name="flags">flags to indicate which type of input occurred - move, button press/release, wheel move, etc.</param>
/// <remarks>x, y are in pixels. If Absolute flag used, are relative to desktop origin.</remarks>
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
private static void SendMouseInput(double x, double y, int data, SendMouseInputFlags flags)
{
//CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Input );
int intflags = (int)flags;
if ((intflags & (int)SendMouseInputFlags.Absolute) != 0)
{
int vscreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int vscreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int vscreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
int vscreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
// Absolute input requires that input is in 'normalized' coords - with the entire
// desktop being (0,0)...(65535,65536). Need to convert input x,y coords to this
// first.
//
// In this normalized world, any pixel on the screen corresponds to a block of values
// of normalized coords - eg. on a 1024x768 screen,
// y pixel 0 corresponds to range 0 to 85.333,
// y pixel 1 corresponds to range 85.333 to 170.666,
// y pixel 2 correpsonds to range 170.666 to 256 - and so on.
// Doing basic scaling math - (x-top)*65536/Width - gets us the start of the range.
// However, because int math is used, this can end up being rounded into the wrong
// pixel. For example, if we wanted pixel 1, we'd get 85.333, but that comes out as
// 85 as an int, which falls into pixel 0's range - and that's where the pointer goes.
// To avoid this, we add on half-a-"screen pixel"'s worth of normalized coords - to
// push us into the middle of any given pixel's range - that's the 65536/(Width*2)
// part of the formula. So now pixel 1 maps to 85+42 = 127 - which is comfortably
// in the middle of that pixel's block.
// The key ting here is that unlike points in coordinate geometry, pixels take up
// space, so are often better treated like rectangles - and if you want to target
// a particular pixel, target its rectangle's midpoint, not its edge.
x = ((x - vscreenLeft) * 65536) / vscreenWidth + 65536 / (vscreenWidth * 2);
y = ((y - vscreenTop) * 65536) / vscreenHeight + 65536 / (vscreenHeight * 2);
intflags |= MOUSEEVENTF_VIRTUALDESK;
}
INPUT mi = new INPUT();
mi.type = Const.INPUT_MOUSE;
mi.union.mouseInput.dx = (int)x;
mi.union.mouseInput.dy = (int)y;
mi.union.mouseInput.mouseData = data;
mi.union.mouseInput.dwFlags = intflags;
mi.union.mouseInput.time = 0;
mi.union.mouseInput.dwExtraInfo = new IntPtr(0);
//Console.WriteLine("Sending");
if (SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
#endregion
#region Public methods
public static Point Loaction()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
/// <summary>
/// Move the mouse to a point.
/// </summary>
/// <param name="pt">The point that the mouse will move to.</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveTo(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
}
/// <summary>
/// Move the mouse to an element.
/// </summary>
/// <param name="el">The element that the mouse will move to</param>
/// <exception cref="NoClickablePointException">If there is not clickable point for the element</exception>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveTo(AutomationElement el)
{
if (el == null)
{
throw new ArgumentNullException("el");
}
MoveTo(el.GetClickablePoint());
}
/// <summary>
/// Move the mouse to a point and click. The primary mouse button will be used
/// this is usually the left button except if the mouse buttons are swaped.
/// </summary>
/// <param name="pt">The point to click at</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveToAndClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, true);
}
/// <summary>
/// Move the mouse to a point and double click. The primary mouse button will be used
/// this is usually the left button except if the mouse buttons are swaped.
/// </summary>
/// <param name="pt">The point to click at</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveToAndDoubleClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, true);
Thread.Sleep(300);
RawClick(pt, true);
}
private static void RawClick(Point pt, bool left)
{
// send SendMouseInput works in term of the phisical mouse buttons, therefore we need
// to check to see if the mouse buttons are swapped because this method need to use the primary
// mouse button.
if (ButtonsSwapped() != left)
{
// the mouse buttons are not swaped the primary is the left
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.LeftDown | SendMouseInputFlags.Absolute);
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.LeftUp | SendMouseInputFlags.Absolute);
}
else
{
// the mouse buttons are swaped so click the right button which as actually the primary
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.RightDown | SendMouseInputFlags.Absolute);
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.RightUp | SendMouseInputFlags.Absolute);
}
}
private static bool ButtonsSwapped()
{
return GetSystemMetrics(SM_SWAPBUTTON) != 0;
}
public static void MoveToAndRightClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, false);
}
public static void Click(Point point)
{
MoveToAndClick(point);
}
private static void Click(AutomationElement element)
{
try
{
MoveToAndClick(element.GetClickablePoint());
}
catch
{
}
}
internal static void DoubleClick(Element element)
{
DoubleClick(element.Ae);
SleepAfter();
}
private static void DoubleClick(AutomationElement element)
{
MoveToAndDoubleClick(element.GetClickablePoint());
}
private static void RightClick(Point point)
{
MoveToAndRightClick(point);
}
#endregion
#region Native types
/// <summary>
/// Flags for Input.SendMouseInput, indicate whether movent took place,
/// or whether buttons were pressed or released.
/// </summary>
[Flags]
public enum SendMouseInputFlags
{
/// <summary>Specifies that the pointer moved.</summary>
Move = 0x0001,
/// <summary>Specifies that the left button was pressed.</summary>
LeftDown = 0x0002,
/// <summary>Specifies that the left button was released.</summary>
LeftUp = 0x0004,
/// <summary>Specifies that the right button was pressed.</summary>
RightDown = 0x0008,
/// <summary>Specifies that the right button was released.</summary>
RightUp = 0x0010,
/// <summary>Specifies that the middle button was pressed.</summary>
MiddleDown = 0x0020,
/// <summary>Specifies that the middle button was released.</summary>
MiddleUp = 0x0040,
/// <summary>Specifies that the x button was pressed.</summary>
XDown = 0x0080,
/// <summary>Specifies that the x button was released. </summary>
XUp = 0x0100,
/// <summary>Specifies that the wheel was moved</summary>
Wheel = 0x0800,
/// <summary>Specifies that x, y are absolute, not relative</summary>
Absolute = 0x8000,
};
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
#endregion
#region Native methods
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(int metric);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT mi, int cbSize);
#endregion
}
}
| |
//
// flowanalyis.cs: The control flow analysis code
//
// Authors:
// Martin Baulig ([email protected])
// Raja R Harinath ([email protected])
// Marek Safar ([email protected])
//
// Copyright 2001, 2002, 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011 Xamarin, Inc.
//
using System;
using System.Text;
using System.Collections.Generic;
namespace Mono.CSharp
{
// <summary>
// This is used by the flow analysis code to keep track of the type of local variables.
//
// The flow code uses a BitVector to keep track of whether a variable has been assigned
// or not. This is easy for fundamental types (int, char etc.) or reference types since
// you can only assign the whole variable as such.
//
// For structs, we also need to keep track of all its fields. To do this, we allocate one
// bit for the struct itself (it's used if you assign/access the whole struct) followed by
// one bit for each of its fields.
//
// This class computes this `layout' for each type.
// </summary>
public class TypeInfo
{
// <summary>
// Total number of bits a variable of this type consumes in the flow vector.
// </summary>
public readonly int TotalLength;
// <summary>
// Number of bits the simple fields of a variable of this type consume
// in the flow vector.
// </summary>
public readonly int Length;
// <summary>
// This is only used by sub-structs.
// </summary>
public readonly int Offset;
// <summary>
// If this is a struct.
// </summary>
public readonly bool IsStruct;
// <summary>
// If this is a struct, all fields which are structs theirselves.
// </summary>
public TypeInfo[] SubStructInfo;
readonly StructInfo struct_info;
static readonly TypeInfo simple_type = new TypeInfo (1);
static TypeInfo ()
{
Reset ();
}
public static void Reset ()
{
StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
}
TypeInfo (int totalLength)
{
this.TotalLength = totalLength;
}
TypeInfo (StructInfo struct_info, int offset)
{
this.struct_info = struct_info;
this.Offset = offset;
this.Length = struct_info.Length;
this.TotalLength = struct_info.TotalLength;
this.SubStructInfo = struct_info.StructFields;
this.IsStruct = true;
}
public int GetFieldIndex (string name)
{
if (struct_info == null)
return 0;
return struct_info [name];
}
public TypeInfo GetStructField (string name)
{
if (struct_info == null)
return null;
return struct_info.GetStructField (name);
}
public static TypeInfo GetTypeInfo (TypeSpec type, IMemberContext context)
{
if (!type.IsStruct)
return simple_type;
TypeInfo info;
Dictionary<TypeSpec, TypeInfo> type_hash;
if (type.BuiltinType > 0) {
// Don't cache built-in types, they are null in most cases except for
// corlib compilation when we need to distinguish between declaration
// and referencing
type_hash = null;
} else {
type_hash = context.Module.TypeInfoCache;
if (type_hash.TryGetValue (type, out info))
return info;
}
var struct_info = StructInfo.GetStructInfo (type, context);
if (struct_info != null) {
info = new TypeInfo (struct_info, 0);
} else {
info = simple_type;
}
if (type_hash != null)
type_hash.Add (type, info);
return info;
}
// <summary>
// A struct's constructor must always assign all fields.
// This method checks whether it actually does so.
// </summary>
public bool IsFullyInitialized (FlowAnalysisContext fc, VariableInfo vi, Location loc)
{
if (struct_info == null)
return true;
bool ok = true;
for (int i = 0; i < struct_info.Count; i++) {
var field = struct_info.Fields[i];
if (!fc.IsStructFieldDefinitelyAssigned (vi, field.Name)) {
var bf = field.MemberDefinition as Property.BackingFieldDeclaration;
if (bf != null) {
if (bf.Initializer != null)
continue;
fc.Report.Error (843, loc,
"An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling the default struct contructor from a constructor initializer",
field.GetSignatureForError ());
ok = false;
continue;
}
fc.Report.Error (171, loc,
"Field `{0}' must be fully assigned before control leaves the constructor",
field.GetSignatureForError ());
ok = false;
}
}
return ok;
}
public override string ToString ()
{
return String.Format ("TypeInfo ({0}:{1}:{2})",
Offset, Length, TotalLength);
}
class StructInfo
{
readonly List<FieldSpec> fields;
public readonly TypeInfo[] StructFields;
public readonly int Length;
public readonly int TotalLength;
public static Dictionary<TypeSpec, StructInfo> field_type_hash;
private Dictionary<string, TypeInfo> struct_field_hash;
private Dictionary<string, int> field_hash;
bool InTransit;
//
// We only need one instance per type
//
StructInfo (TypeSpec type, IMemberContext context)
{
field_type_hash.Add (type, this);
fields = MemberCache.GetAllFieldsForDefiniteAssignment (type, context);
struct_field_hash = new Dictionary<string, TypeInfo> ();
field_hash = new Dictionary<string, int> (fields.Count);
StructFields = new TypeInfo[fields.Count];
StructInfo[] sinfo = new StructInfo[fields.Count];
InTransit = true;
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (field.MemberType.IsStruct)
sinfo [i] = GetStructInfo (field.MemberType, context);
if (sinfo [i] == null)
field_hash.Add (field.Name, ++Length);
else if (sinfo [i].InTransit) {
sinfo [i] = null;
return;
}
}
InTransit = false;
TotalLength = Length + 1;
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (sinfo [i] == null)
continue;
field_hash.Add (field.Name, TotalLength);
StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
struct_field_hash.Add (field.Name, StructFields [i]);
TotalLength += sinfo [i].TotalLength;
}
}
public int Count {
get {
return fields.Count;
}
}
public List<FieldSpec> Fields {
get {
return fields;
}
}
public int this [string name] {
get {
int val;
if (!field_hash.TryGetValue (name, out val))
return 0;
return val;
}
}
public TypeInfo GetStructField (string name)
{
TypeInfo ti;
if (struct_field_hash.TryGetValue (name, out ti))
return ti;
return null;
}
public static StructInfo GetStructInfo (TypeSpec type, IMemberContext context)
{
if (type.BuiltinType > 0 && type != context.CurrentType)
return null;
StructInfo info;
if (field_type_hash.TryGetValue (type, out info))
return info;
return new StructInfo (type, context);
}
}
}
//
// This is used by definite assignment analysis code to store information about a local variable
// or parameter. Depending on the variable's type, we need to allocate one or more elements
// in the BitVector - if it's a fundamental or reference type, we just need to know whether
// it has been assigned or not, but for structs, we need this information for each of its fields.
//
public class VariableInfo
{
readonly string Name;
readonly TypeInfo TypeInfo;
// <summary>
// The bit offset of this variable in the flow vector.
// </summary>
readonly int Offset;
// <summary>
// The number of bits this variable needs in the flow vector.
// The first bit always specifies whether the variable as such has been assigned while
// the remaining bits contain this information for each of a struct's fields.
// </summary>
readonly int Length;
// <summary>
// If this is a parameter of local variable.
// </summary>
public bool IsParameter;
VariableInfo[] sub_info;
VariableInfo (string name, TypeSpec type, int offset, IMemberContext context)
{
this.Name = name;
this.Offset = offset;
this.TypeInfo = TypeInfo.GetTypeInfo (type, context);
Length = TypeInfo.TotalLength;
Initialize ();
}
VariableInfo (VariableInfo parent, TypeInfo type)
{
this.Name = parent.Name;
this.TypeInfo = type;
this.Offset = parent.Offset + type.Offset;
this.Length = type.TotalLength;
this.IsParameter = parent.IsParameter;
Initialize ();
}
void Initialize ()
{
TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
if (sub_fields != null) {
sub_info = new VariableInfo [sub_fields.Length];
for (int i = 0; i < sub_fields.Length; i++) {
if (sub_fields [i] != null)
sub_info [i] = new VariableInfo (this, sub_fields [i]);
}
} else
sub_info = new VariableInfo [0];
}
public static VariableInfo Create (BlockContext bc, LocalVariable variable)
{
var info = new VariableInfo (variable.Name, variable.Type, bc.AssignmentInfoOffset, bc);
bc.AssignmentInfoOffset += info.Length;
return info;
}
public static VariableInfo Create (BlockContext bc, Parameter parameter)
{
var info = new VariableInfo (parameter.Name, parameter.Type, bc.AssignmentInfoOffset, bc) {
IsParameter = true
};
bc.AssignmentInfoOffset += info.Length;
return info;
}
public bool IsAssigned (DefiniteAssignmentBitSet vector)
{
if (vector == null)
return true;
if (vector [Offset])
return true;
// Unless this is a struct
if (!TypeInfo.IsStruct)
return false;
//
// Following case cannot be handled fully by SetStructFieldAssigned
// because we may encounter following case
//
// struct A { B b }
// struct B { int value; }
//
// setting a.b.value is propagated only to B's vector and not upwards to possible parents
//
//
// Each field must be assigned
//
for (int i = Offset + 1; i <= TypeInfo.Length + Offset; i++) {
if (!vector[i])
return false;
}
// Ok, now check all fields which are structs.
for (int i = 0; i < sub_info.Length; i++) {
VariableInfo sinfo = sub_info[i];
if (sinfo == null)
continue;
if (!sinfo.IsAssigned (vector))
return false;
}
vector.Set (Offset);
return true;
}
public bool IsEverAssigned { get; set; }
public bool IsFullyInitialized (FlowAnalysisContext fc, Location loc)
{
return TypeInfo.IsFullyInitialized (fc, this, loc);
}
public bool IsStructFieldAssigned (DefiniteAssignmentBitSet vector, string field_name)
{
int field_idx = TypeInfo.GetFieldIndex (field_name);
if (field_idx == 0)
return true;
return vector [Offset + field_idx];
}
public void SetAssigned (DefiniteAssignmentBitSet vector, bool generatedAssignment)
{
if (Length == 1)
vector.Set (Offset);
else
vector.Set (Offset, Length);
if (!generatedAssignment)
IsEverAssigned = true;
}
public void SetStructFieldAssigned (DefiniteAssignmentBitSet vector, string field_name)
{
if (vector [Offset])
return;
int field_idx = TypeInfo.GetFieldIndex (field_name);
if (field_idx == 0)
return;
var complex_field = TypeInfo.GetStructField (field_name);
if (complex_field != null) {
vector.Set (Offset + complex_field.Offset, complex_field.TotalLength);
} else {
vector.Set (Offset + field_idx);
}
IsEverAssigned = true;
//
// Each field must be assigned before setting master bit
//
for (int i = Offset + 1; i < TypeInfo.TotalLength + Offset; i++) {
if (!vector[i])
return;
}
//
// Set master struct flag to assigned when all tested struct
// fields have been assigned
//
vector.Set (Offset);
}
public VariableInfo GetStructFieldInfo (string fieldName)
{
TypeInfo type = TypeInfo.GetStructField (fieldName);
if (type == null)
return null;
return new VariableInfo (this, type);
}
public override string ToString ()
{
return String.Format ("Name={0} Offset={1} Length={2} {3})", Name, Offset, Length, TypeInfo);
}
}
public struct Reachability
{
readonly bool unreachable;
Reachability (bool unreachable)
{
this.unreachable = unreachable;
}
public bool IsUnreachable {
get {
return unreachable;
}
}
public static Reachability CreateUnreachable ()
{
return new Reachability (true);
}
public static Reachability operator & (Reachability a, Reachability b)
{
return new Reachability (a.unreachable && b.unreachable);
}
public static Reachability operator | (Reachability a, Reachability b)
{
return new Reachability (a.unreachable | b.unreachable);
}
}
//
// Special version of bit array. Many operations can be simplified because
// we are always dealing with arrays of same sizes
//
public class DefiniteAssignmentBitSet
{
const uint copy_on_write_flag = 1u << 31;
uint bits;
// Used when bits overflows
int[] large_bits;
public static readonly DefiniteAssignmentBitSet Empty = new DefiniteAssignmentBitSet (0);
public DefiniteAssignmentBitSet (int length)
{
if (length > 31)
large_bits = new int[(length + 31) / 32];
}
public DefiniteAssignmentBitSet (DefiniteAssignmentBitSet source)
{
if (source.large_bits != null) {
large_bits = source.large_bits;
bits = source.bits | copy_on_write_flag;
} else {
bits = source.bits & ~copy_on_write_flag;
}
}
public static DefiniteAssignmentBitSet operator & (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
{
if (IsEqual (a, b))
return a;
DefiniteAssignmentBitSet res;
if (a.large_bits == null) {
res = new DefiniteAssignmentBitSet (a);
res.bits &= (b.bits & ~copy_on_write_flag);
return res;
}
res = new DefiniteAssignmentBitSet (a);
res.Clone ();
var dest = res.large_bits;
var src = b.large_bits;
for (int i = 0; i < dest.Length; ++i) {
dest[i] &= src[i];
}
return res;
}
public static DefiniteAssignmentBitSet operator | (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
{
if (IsEqual (a, b))
return a;
DefiniteAssignmentBitSet res;
if (a.large_bits == null) {
res = new DefiniteAssignmentBitSet (a);
res.bits |= b.bits;
res.bits &= ~copy_on_write_flag;
return res;
}
res = new DefiniteAssignmentBitSet (a);
res.Clone ();
var dest = res.large_bits;
var src = b.large_bits;
for (int i = 0; i < dest.Length; ++i) {
dest[i] |= src[i];
}
return res;
}
public static DefiniteAssignmentBitSet And (List<DefiniteAssignmentBitSet> das)
{
if (das.Count == 0)
throw new ArgumentException ("Empty das");
DefiniteAssignmentBitSet res = das[0];
for (int i = 1; i < das.Count; ++i) {
res &= das[i];
}
return res;
}
bool CopyOnWrite {
get {
return (bits & copy_on_write_flag) != 0;
}
}
int Length {
get {
return large_bits == null ? 31 : large_bits.Length * 32;
}
}
public void Set (int index)
{
if (CopyOnWrite && !this[index])
Clone ();
SetBit (index);
}
public void Set (int index, int length)
{
for (int i = 0; i < length; ++i) {
if (CopyOnWrite && !this[index + i])
Clone ();
SetBit (index + i);
}
}
public bool this[int index] {
get {
return GetBit (index);
}
}
public override string ToString ()
{
var length = Length;
StringBuilder sb = new StringBuilder (length);
for (int i = 0; i < length; ++i) {
sb.Append (this[i] ? '1' : '0');
}
return sb.ToString ();
}
void Clone ()
{
large_bits = (int[]) large_bits.Clone ();
}
bool GetBit (int index)
{
return large_bits == null ?
(bits & (1 << index)) != 0 :
(large_bits[index >> 5] & (1 << (index & 31))) != 0;
}
void SetBit (int index)
{
if (large_bits == null)
bits = (uint) ((int) bits | (1 << index));
else
large_bits[index >> 5] |= (1 << (index & 31));
}
static bool IsEqual (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
{
if (a.large_bits == null)
return (a.bits & ~copy_on_write_flag) == (b.bits & ~copy_on_write_flag);
for (int i = 0; i < a.large_bits.Length; ++i) {
if (a.large_bits[i] != b.large_bits[i])
return false;
}
return true;
}
public static bool IsIncluded (DefiniteAssignmentBitSet set, DefiniteAssignmentBitSet test)
{
var set_bits = set.large_bits;
if (set_bits == null)
return (set.bits & test.bits & ~copy_on_write_flag) == (set.bits & ~copy_on_write_flag);
var test_bits = test.large_bits;
for (int i = 0; i < set_bits.Length; ++i) {
if ((set_bits[i] & test_bits[i]) != set_bits[i])
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that reads both primitive values and non-cyclical object graphs from a stream that was constructed using
/// the ObjectWriter class.
/// </summary>
internal sealed class ObjectReader : ObjectReaderWriterBase, IDisposable
{
private readonly BinaryReader _reader;
private readonly ObjectReaderData _dataMap;
private readonly ObjectBinder _binder;
internal ObjectReader(
Stream stream,
ObjectReaderData defaultData = null,
ObjectBinder binder = null)
{
// String serialization assumes both reader and writer to be of the same endianness.
// It can be adjusted for BigEndian if needed.
Debug.Assert(BitConverter.IsLittleEndian);
_reader = new BinaryReader(stream, Encoding.UTF8);
_dataMap = new ObjectReaderData(defaultData);
_binder = binder;
}
public void Dispose()
{
_dataMap.Dispose();
}
/// <summary>
/// Read a Boolean value from the stream. This value must have been written using <see cref="ObjectWriter.WriteBoolean(bool)"/>.
/// </summary>
public bool ReadBoolean()
{
return _reader.ReadBoolean();
}
/// <summary>
/// Read a Byte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteByte(byte)"/>.
/// </summary>
public byte ReadByte()
{
return _reader.ReadByte();
}
/// <summary>
/// Read a Char value from the stream. This value must have been written using <see cref="ObjectWriter.WriteChar(char)"/>.
/// </summary>
public char ReadChar()
{
// char was written as UInt16 because BinaryWriter fails on characters that are unicode surrogates.
return (char)_reader.ReadUInt16();
}
/// <summary>
/// Read a Decimal value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDecimal(decimal)"/>.
/// </summary>
public decimal ReadDecimal()
{
return _reader.ReadDecimal();
}
/// <summary>
/// Read a Double value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDouble(double)"/>.
/// </summary>
public double ReadDouble()
{
return _reader.ReadDouble();
}
/// <summary>
/// Read a Single value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSingle(float)"/>.
/// </summary>
public float ReadSingle()
{
return _reader.ReadSingle();
}
/// <summary>
/// Read a Int32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt32(int)"/>.
/// </summary>
public int ReadInt32()
{
return _reader.ReadInt32();
}
/// <summary>
/// Read a Int64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt64(long)"/>.
/// </summary>
public long ReadInt64()
{
return _reader.ReadInt64();
}
/// <summary>
/// Read a SByte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSByte(sbyte)"/>.
/// </summary>
public sbyte ReadSByte()
{
return _reader.ReadSByte();
}
/// <summary>
/// Read a Int16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt16(short)"/>.
/// </summary>
public short ReadInt16()
{
return _reader.ReadInt16();
}
/// <summary>
/// Read a UInt32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt32(uint)"/>.
/// </summary>
public uint ReadUInt32()
{
return _reader.ReadUInt32();
}
/// <summary>
/// Read a UInt64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt64(ulong)"/>.
/// </summary>
public ulong ReadUInt64()
{
return _reader.ReadUInt64();
}
/// <summary>
/// Read a UInt16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt16(ushort)"/>.
/// </summary>
public ushort ReadUInt16()
{
return _reader.ReadUInt16();
}
/// <summary>
/// Read a DateTime value from the stream. This value must have been written using the <see cref="ObjectWriter.WriteDateTime(DateTime)"/>.
/// </summary>
public DateTime ReadDateTime()
{
return DateTime.FromBinary(this.ReadInt64());
}
/// <summary>
/// Read a compressed 30-bit integer value from the stream. This value must have been written using <see cref="ObjectWriter.WriteCompressedUInt(uint)"/>.
/// </summary>
public uint ReadCompressedUInt()
{
var info = _reader.ReadByte();
byte marker = (byte)(info & ByteMarkerMask);
byte byte0 = (byte)(info & ~ByteMarkerMask);
if (marker == Byte1Marker)
{
return byte0;
}
if (marker == Byte2Marker)
{
var byte1 = _reader.ReadByte();
return (((uint)byte0) << 8) | byte1;
}
if (marker == Byte4Marker)
{
var byte1 = _reader.ReadByte();
var byte2 = _reader.ReadByte();
var byte3 = _reader.ReadByte();
return (((uint)byte0) << 24) | (((uint)byte1) << 16) | (((uint)byte2) << 8) | byte3;
}
throw ExceptionUtilities.UnexpectedValue(marker);
}
/// <summary>
/// Read a value from the stream. The value must have been written using ObjectWriter.WriteValue.
/// </summary>
public object ReadValue()
{
var kind = (DataKind)_reader.ReadByte();
switch (kind)
{
case DataKind.Null:
return null;
case DataKind.Boolean_T:
return Boxes.BoxedTrue;
case DataKind.Boolean_F:
return Boxes.BoxedFalse;
case DataKind.Int8:
return _reader.ReadSByte();
case DataKind.UInt8:
return _reader.ReadByte();
case DataKind.Int16:
return _reader.ReadInt16();
case DataKind.UInt16:
return _reader.ReadUInt16();
case DataKind.Int32:
return _reader.ReadInt32();
case DataKind.Int32_B:
return (int)_reader.ReadByte();
case DataKind.Int32_S:
return (int)_reader.ReadUInt16();
case DataKind.Int32_Z:
return Boxes.BoxedInt32Zero;
case DataKind.UInt32:
return _reader.ReadUInt32();
case DataKind.Int64:
return _reader.ReadInt64();
case DataKind.UInt64:
return _reader.ReadUInt64();
case DataKind.Float4:
return _reader.ReadSingle();
case DataKind.Float8:
return _reader.ReadDouble();
case DataKind.Decimal:
return _reader.ReadDecimal();
case DataKind.DateTime:
return this.ReadDateTime();
case DataKind.Char:
return this.ReadChar();
case DataKind.StringUtf8:
case DataKind.StringUtf16:
case DataKind.StringRef:
case DataKind.StringRef_B:
case DataKind.StringRef_S:
return ReadString(kind);
case DataKind.Object_W:
case DataKind.ObjectRef:
case DataKind.ObjectRef_B:
case DataKind.ObjectRef_S:
return ReadObject(kind);
case DataKind.Type:
case DataKind.TypeRef:
case DataKind.TypeRef_B:
case DataKind.TypeRef_S:
return ReadType(kind);
case DataKind.Enum:
return ReadEnum();
case DataKind.Array:
case DataKind.Array_0:
case DataKind.Array_1:
case DataKind.Array_2:
case DataKind.Array_3:
return ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
/// <summary>
/// Read a String value from the stream. This value must have been written using ObjectWriter.WriteString.
/// </summary>
public string ReadString()
{
var kind = (DataKind)_reader.ReadByte();
return kind == DataKind.Null ? null : ReadString(kind);
}
private string ReadString(DataKind kind)
{
switch (kind)
{
case DataKind.StringRef_B:
return (string)_dataMap.GetValue(_reader.ReadByte());
case DataKind.StringRef_S:
return (string)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.StringRef:
return (string)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.StringUtf16:
case DataKind.StringUtf8:
return ReadStringLiteral(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private unsafe string ReadStringLiteral(DataKind kind)
{
int id = _dataMap.GetNextId();
string value;
if (kind == DataKind.StringUtf8)
{
value = _reader.ReadString();
}
else
{
// This is rare, just allocate UTF16 bytes for simplicity.
int characterCount = (int)ReadCompressedUInt();
byte[] bytes = _reader.ReadBytes(characterCount * sizeof(char));
fixed (byte* bytesPtr = bytes)
{
value = new string((char*)bytesPtr, 0, characterCount);
}
}
_dataMap.AddValue(id, value);
return value;
}
private Array ReadArray(DataKind kind)
{
int length;
switch (kind)
{
case DataKind.Array_0:
length = 0;
break;
case DataKind.Array_1:
length = 1;
break;
case DataKind.Array_2:
length = 2;
break;
case DataKind.Array_3:
length = 3;
break;
default:
length = (int)this.ReadCompressedUInt();
break;
}
var elementKind = (DataKind)_reader.ReadByte();
// optimization for primitive type array
if (s_reverseTypeMap.TryGetValue(elementKind, out var elementType))
{
return this.ReadPrimitiveTypeArrayElements(elementType, elementKind, length);
}
// custom type case
elementType = this.ReadType(elementKind);
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
{
var value = this.ReadValue();
array.SetValue(value, i);
}
return array;
}
private Array ReadPrimitiveTypeArrayElements(Type type, DataKind kind, int length)
{
Debug.Assert(s_reverseTypeMap[kind] == type);
// optimizations for supported array type by binary reader
if (type == typeof(byte))
{
return _reader.ReadBytes(length);
}
if (type == typeof(char))
{
return _reader.ReadChars(length);
}
// optimizations for string where object reader/writer has its own mechanism to
// reduce duplicated strings
if (type == typeof(string))
{
return ReadPrimitiveTypeArrayElements(length, ReadString);
}
if (type == typeof(bool))
{
return ReadBooleanArray(length);
}
// otherwise, read elements directly from underlying binary writer
switch (kind)
{
case DataKind.Int8:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadSByte);
case DataKind.Int16:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt16);
case DataKind.Int32:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt32);
case DataKind.Int64:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt64);
case DataKind.UInt16:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt16);
case DataKind.UInt32:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt32);
case DataKind.UInt64:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt64);
case DataKind.Float4:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadSingle);
case DataKind.Float8:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadDouble);
case DataKind.Decimal:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadDecimal);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private bool[] ReadBooleanArray(int length)
{
if (length == 0)
{
// simple check
return Array.Empty<bool>();
}
var array = new bool[length];
var wordLength = BitVector.WordsRequired(length);
var count = 0;
for (var i = 0; i < wordLength; i++)
{
var word = _reader.ReadUInt32();
for (var p = 0; p < BitVector.BitsPerWord; p++)
{
if (count >= length)
{
return array;
}
array[count++] = BitVector.IsTrue(word, p);
}
}
return array;
}
private static T[] ReadPrimitiveTypeArrayElements<T>(int length, Func<T> read)
{
if (length == 0)
{
// quick check
return Array.Empty<T>();
}
var array = new T[length];
for (var i = 0; i < array.Length; i++)
{
array[i] = read();
}
return array;
}
private Type ReadType()
{
var kind = (DataKind)_reader.ReadByte();
return ReadType(kind);
}
private Type ReadType(DataKind kind)
{
switch (kind)
{
case DataKind.TypeRef_B:
return (Type)_dataMap.GetValue(_reader.ReadByte());
case DataKind.TypeRef_S:
return (Type)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.TypeRef:
return (Type)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.Type:
int id = _dataMap.GetNextId();
var assemblyName = this.ReadString();
var typeName = this.ReadString();
if (_binder == null)
{
throw NoBinderException(typeName);
}
var type = _binder.GetType(assemblyName, typeName);
_dataMap.AddValue(id, type);
return type;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadEnum()
{
var enumType = this.ReadType();
var type = Enum.GetUnderlyingType(enumType);
if (type == typeof(int))
{
return Enum.ToObject(enumType, _reader.ReadInt32());
}
if (type == typeof(short))
{
return Enum.ToObject(enumType, _reader.ReadInt16());
}
if (type == typeof(byte))
{
return Enum.ToObject(enumType, _reader.ReadByte());
}
if (type == typeof(long))
{
return Enum.ToObject(enumType, _reader.ReadInt64());
}
if (type == typeof(sbyte))
{
return Enum.ToObject(enumType, _reader.ReadSByte());
}
if (type == typeof(ushort))
{
return Enum.ToObject(enumType, _reader.ReadUInt16());
}
if (type == typeof(uint))
{
return Enum.ToObject(enumType, _reader.ReadUInt32());
}
if (type == typeof(ulong))
{
return Enum.ToObject(enumType, _reader.ReadUInt64());
}
throw ExceptionUtilities.UnexpectedValue(enumType);
}
private object ReadObject(DataKind kind)
{
switch (kind)
{
case DataKind.ObjectRef_B:
return _dataMap.GetValue(_reader.ReadByte());
case DataKind.ObjectRef_S:
return _dataMap.GetValue(_reader.ReadUInt16());
case DataKind.ObjectRef:
return _dataMap.GetValue(_reader.ReadInt32());
case DataKind.Object_W:
return this.ReadReadableObject();
case DataKind.Array:
return this.ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadReadableObject()
{
int id = _dataMap.GetNextId();
Type type = this.ReadType();
var instance = CreateInstance(type);
_dataMap.AddValue(id, instance);
return instance;
}
private object CreateInstance(Type type)
{
if (_binder == null)
{
return NoBinderException(type.FullName);
}
var reader = _binder.GetReader(type);
if (reader == null)
{
return NoReaderException(type.FullName);
}
return reader(this);
}
private static Exception NoBinderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoBinderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_no_binder_supplied, typeName));
#endif
}
private static Exception NoReaderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoReaderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_it_has_no_deserialization_reader, typeName));
#endif
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Symbology;
using NetTopologySuite.Geometries;
namespace DotSpatial.Controls
{
/// <summary>
/// This is a specialized FeatureLayer that specifically handles point drawing.
/// </summary>
public class MapPointLayer : PointLayer, IMapPointLayer
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MapPointLayer"/> class.
/// This creates a blank MapPointLayer with the DataSet set to an empty new featureset of the Point featuretype.
/// </summary>
public MapPointLayer()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapPointLayer"/> class.
/// </summary>
/// <param name="featureSet">The point feature set used as data source.</param>
public MapPointLayer(IFeatureSet featureSet)
: base(featureSet)
{
// this simply handles the default case where no status messages are requested
Configure();
OnFinishedLoading();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapPointLayer"/> class.
/// Creates a new instance of the point layer where the container is specified.
/// </summary>
/// <param name="featureSet">The point feature set used as data source.</param>
/// <param name="container">An IContainer that the point layer should be created in.</param>
public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container)
: base(featureSet, container, null)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapPointLayer"/> class.
/// Creates a new instance of the point layer where the container is specified.
/// </summary>
/// <param name="featureSet">The point feature set used as data source.</param>
/// <param name="container">An IContainer that the point layer should be created in.</param>
/// <param name="notFinished">Indicates whether the OnFinishedLoading event should be suppressed after loading finished.</param>
public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished)
: base(featureSet, container, null)
{
Configure();
if (!notFinished) OnFinishedLoading();
}
#endregion
#region Events
/// <summary>
/// Occurs when drawing content has changed on the buffer for this layer
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image BackBuffer { get; set; }
/// <summary>
/// Gets or sets the current buffer.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Envelope BufferEnvelope { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets or sets the label layer that is associated with this point layer.
/// </summary>
[ShallowCopy]
public new IMapLabelLayer LabelLayer
{
get
{
return base.LabelLayer as IMapLabelLayer;
}
set
{
base.LabelLayer = value;
}
}
#endregion
#region Methods
/// <summary>
/// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not
/// does not generate a point layer, an exception will be thrown.
/// </summary>
/// <param name="fileName">A string fileName to create a point layer for.</param>
/// <param name="progressHandler">Any valid implementation of IProgressHandler for receiving progress messages.</param>
/// <returns>A GeoPointLayer created from the specified fileName.</returns>
public static new MapPointLayer OpenFile(string fileName, IProgressHandler progressHandler)
{
ILayer fl = LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);
return fl as MapPointLayer;
}
/// <summary>
/// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not
/// does not generate a point layer, an exception will be thrown.
/// </summary>
/// <param name="fileName">A string fileName to create a point layer for.</param>
/// <returns>A GeoPointLayer created from the specified fileName.</returns>
public static new MapPointLayer OpenFile(string fileName)
{
IFeatureLayer fl = LayerManager.DefaultLayerManager.OpenVectorLayer(fileName);
return fl as MapPointLayer;
}
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (BackBuffer == null) return;
Graphics g = Graphics.FromImage(BackBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// This is testing the idea of using an input parameter type that is marked as out
/// instead of a return type.
/// </summary>
/// <param name="result">The result of the creation.</param>
/// <returns>Boolean, true if a layer can be created.</returns>
public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result)
{
bool resultOk = CreateLayerFromSelectedFeatures(out MapPointLayer temp);
result = temp;
return resultOk;
}
/// <summary>
/// This is the strong typed version of the same process that is specific to geo point layers.
/// </summary>
/// <param name="result">The new GeoPointLayer to be created.</param>
/// <returns>Boolean, true if there were any values in the selection.</returns>
public virtual bool CreateLayerFromSelectedFeatures(out MapPointLayer result)
{
result = null;
if (Selection == null || Selection.Count == 0) return false;
FeatureSet fs = Selection.ToFeatureSet();
result = new MapPointLayer(fs);
return true;
}
/// <summary>
/// If EditMode is true, then this method is used for drawing.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks, bool selected)
{
if (!useChunks || features.Count < ChunkSize)
{
DrawFeatures(args, features, selected);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int groupSize = ChunkSize;
if (chunk == numChunks - 1) groupSize = count - (chunk * ChunkSize);
List<IFeature> subset = features.GetRange(chunk * ChunkSize, groupSize);
DrawFeatures(args, subset, selected);
if (numChunks <= 0 || chunk >= numChunks - 1) continue;
FinishDrawing();
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
/// <summary>
/// If EditMode is false, then this method is used for drawing.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="indices">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks, bool selected)
{
if (!useChunks)
{
DrawFeatures(args, indices, selected);
return;
}
int count = indices.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize);
DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures), selected);
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space.</param>
/// <param name="regions">The geographic regions to draw.</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawRegions(MapArgs args, List<Extent> regions, bool selected)
{
// First determine the number of features we are talking about based on region.
List<Rectangle> clipRects = args.ProjToPixel(regions);
if (EditMode)
{
List<IFeature> drawList = new List<IFeature>();
foreach (Extent region in regions)
{
if (region != null)
{
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawList = drawList.Union(DataSet.Select(region)).ToList();
}
}
DrawFeatures(args, drawList, clipRects, true, selected);
}
else
{
List<int> drawList = new List<int>();
double[] verts = DataSet.Vertex;
if (DataSet.FeatureType == FeatureType.Point)
{
for (int shp = 0; shp < verts.Length / 2; shp++)
{
foreach (Extent extent in regions)
{
if (extent.Intersects(verts[shp * 2], verts[(shp * 2) + 1]))
{
drawList.Add(shp);
}
}
}
}
else
{
List<ShapeRange> shapes = DataSet.ShapeIndices;
for (int shp = 0; shp < shapes.Count; shp++)
{
foreach (Extent region in regions)
{
if (!shapes[shp].Extent.Intersects(region)) continue;
drawList.Add(shp);
break;
}
}
}
DrawFeatures(args, drawList, clipRects, true, selected);
}
}
/// <summary>
/// Indicates that the drawing process has been finalized and swaps the back buffer
/// to the front buffer.
/// </summary>
public void FinishDrawing()
{
OnFinishDrawing();
if (Buffer != null && Buffer != BackBuffer) Buffer.Dispose();
Buffer = BackBuffer;
}
/// <summary>
/// Copies any current content to the back buffer so that drawing should occur on the
/// back buffer (instead of the fore-buffer). Calling draw methods without
/// calling this may cause exceptions.
/// </summary>
/// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer
/// where drawing will be taking place.</param>
public void StartDrawing(bool preserve)
{
Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
if (Buffer?.Width == backBuffer.Width && Buffer.Height == backBuffer.Height && preserve)
{
Graphics g = Graphics.FromImage(backBuffer);
g.DrawImageUnscaled(Buffer, 0, 0);
}
if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose();
BackBuffer = backBuffer;
OnStartDrawing();
}
/// <summary>
/// Fires the OnBufferChanged event.
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels.</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
ClipArgs e = new ClipArgs(clipRectangles);
BufferChanged(this, e);
}
}
/// <summary>
/// A default method to generate a label layer.
/// </summary>
protected override void OnCreateLabels()
{
LabelLayer = new MapLabelLayer(this);
}
/// <summary>
/// Indiciates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
private void Configure()
{
ChunkSize = 50000;
}
// This draws the individual point features
private void DrawFeatures(MapArgs e, IEnumerable<int> indices, bool selected)
{
if (selected && (!DrawnStatesNeeded || !DrawnStates.Any(_ => _.Selected))) return; // there are no selected features
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
Matrix origTransform = g.Transform;
FeatureType featureType = DataSet.FeatureType;
if (!DrawnStatesNeeded)
{
if (Symbology == null || Symbology.Categories.Count == 0) return;
FastDrawnState state = new FastDrawnState(false, Symbology.Categories[0]);
IPointSymbolizer ps = (state.Category as IPointCategory)?.Symbolizer;
if (ps == null) return;
double[] vertices = DataSet.Vertex;
foreach (int index in indices)
{
if (featureType == FeatureType.Point)
{
DrawPoint(vertices[index * 2], vertices[(index * 2) + 1], e, ps, g, origTransform);
}
else
{
// multi-point
ShapeRange range = DataSet.ShapeIndices[index];
for (int i = range.StartIndex; i <= range.EndIndex(); i++)
{
DrawPoint(vertices[i * 2], vertices[(i * 2) + 1], e, ps, g, origTransform);
}
}
}
}
else
{
FastDrawnState[] states = DrawnStates;
var indexList = indices as IList<int> ?? indices.ToList();
if (indexList.Max() >= states.Length)
{
AssignFastDrawnStates();
states = DrawnStates;
}
double[] vertices = DataSet.Vertex;
foreach (int index in indexList)
{
if (index >= states.Length) break;
FastDrawnState state = states[index];
if (!state.Visible || state.Category == null) continue;
if (selected && !state.Selected) continue;
if (!(state.Category is IPointCategory pc)) continue;
IPointSymbolizer ps = selected ? pc.SelectionSymbolizer : pc.Symbolizer;
if (ps == null) continue;
if (featureType == FeatureType.Point)
{
DrawPoint(vertices[index * 2], vertices[(index * 2) + 1], e, ps, g, origTransform);
}
else
{
ShapeRange range = DataSet.ShapeIndices[index];
for (int i = range.StartIndex; i <= range.EndIndex(); i++)
{
DrawPoint(vertices[i * 2], vertices[(i * 2) + 1], e, ps, g, origTransform);
}
}
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
// This draws the individual point features
private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features, bool selected)
{
IDictionary<IFeature, IDrawnState> states = DrawingFilter.DrawnStates;
if (states == null) return;
if (selected && !states.Any(_ => _.Value.IsSelected)) return;
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
Matrix origTransform = g.Transform;
foreach (IFeature feature in features)
{
if (!states.ContainsKey(feature)) continue;
IDrawnState ds = states[feature];
if (ds == null || !ds.IsVisible || ds.SchemeCategory == null) continue;
if (selected && !ds.IsSelected) continue;
if (!(ds.SchemeCategory is IPointCategory pc)) continue;
IPointSymbolizer ps = selected ? pc.SelectionSymbolizer : pc.Symbolizer;
if (ps == null) continue;
foreach (Coordinate c in feature.Geometry.Coordinates)
{
DrawPoint(c.X, c.Y, e, ps, g, origTransform);
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
/// <summary>
/// Draws a point at the given location.
/// </summary>
/// <param name="ptX">X-Coordinate of the point, that should be drawn.</param>
/// <param name="ptY">Y-Coordinate of the point, that should be drawn.</param>
/// <param name="e">MapArgs for calculating the scaleSize.</param>
/// <param name="ps">PointSymbolizer with which the point gets drawn.</param>
/// <param name="g">Graphics-Object that should be used by the PointSymbolizer.</param>
/// <param name="origTransform">The original transformation that is used to position the point.</param>
private void DrawPoint(double ptX, double ptY, MapArgs e, IPointSymbolizer ps, Graphics g, Matrix origTransform)
{
var x = Convert.ToInt32((ptX - e.MinX) * e.Dx);
var y = Convert.ToInt32((e.MaxY - ptY) * e.Dy);
double scaleSize = ps.GetScale(e);
Matrix shift = origTransform.Clone();
shift.Translate(x, y);
g.Transform = shift;
ps.Draw(g, scaleSize);
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXWSFOLD
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This scenario is designed to verify UpdateFolder operation.
/// </summary>
[TestClass]
public class S06_UpdateFolder : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the test class.
/// </summary>
/// <param name="testContext">Context to initialize.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clean up the test class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test cases
/// <summary>
/// This test case verifies requirements related to UpdateFolder operation via creating a folder and updating it with SetFolderFieldType property.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC01_UpdateFolder()
{
#region Create a new folder in the inbox folder.
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
FolderIdType folderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
this.NewCreatedFolderIds.Add(folderId);
#endregion
#region Update Folder Operation.
// UpdateFolder request.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "SetFolderField", folderId);
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the response.
Common.CheckOperationSuccess(updateFolderResponse, 1, this.Site);
string updateNameInRequest = ((SetFolderFieldType)updateFolderRequest.FolderChanges[0].Updates[0]).Item1.DisplayName;
#endregion
#region Get the updated folder.
// GetFolder request.
GetFolderType getUpdatedFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folderId);
// Get the updated folder.
GetFolderResponseType getFolderResponse = this.FOLDAdapter.GetFolder(getUpdatedFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getFolderResponse, 1, this.Site);
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getFolderResponse.ResponseMessages.Items[0];
FolderType gotFolderInfo = (FolderType)allFolders.Folders[0];
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R46444");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R46444
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
46444,
@"[In UpdateFolder Operation]A successful UpdateFolder operation request returns an UpdateFolderResponse element with the ResponseClass attribute of the UpdateFolderResponseMessage element set to ""Success"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R4644");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R4644
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.NoError,
updateFolderResponse.ResponseMessages.Items[0].ResponseCode,
4644,
@"[In UpdateFolder Operation]A successful UpdateFolder operation request returns an UpdateFolderResponse element with the ResponseCode element of the UpdateFolderResponse element set to ""NoError"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R8902");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R8902
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
8902,
@"[In t:FolderChangeType Complex Type]FolderId specifies the folder identifier and change key.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R582");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R582
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
582,
@"[In m:UpdateFolderType Complex Type]The UpdateFolderType complex type specifies a request message to update folders in a mailbox. ");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R534");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R534
// Set a property on a FolderType folder successfully, indicates that Folder represents a regular folder.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
534,
@"[In t:SetFolderFieldType Complex Type]Folder represents a regular folder in the server database.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R9301");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R9301
this.Site.CaptureRequirementIfAreEqual<string>(
updateNameInRequest,
gotFolderInfo.DisplayName,
9301,
@"[In t:FolderChangeType Complex Type][Updates] Specifies a collection of changes to a folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R546");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R546
this.Site.CaptureRequirementIfAreEqual<string>(
updateNameInRequest,
gotFolderInfo.DisplayName,
546,
@"[In t:FolderChangeType Complex Type]The FolderChangeType complex type specifies a collection of changes to be performed on a single folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R5051");
// All folders updated successfully!
this.Site.CaptureRequirement(
5051,
@"[In m:UpdateFolderType Complex Type]FolderChanges represents an array of folders to be updated.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R531");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R531
this.Site.CaptureRequirementIfAreEqual<string>(
updateNameInRequest,
gotFolderInfo.DisplayName,
531,
@"[In t:NonEmptyArrayOfFolderChangesType Complex Type]FolderChange represents a collection of changes to be performed on a single folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R5251");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R5251
this.Site.CaptureRequirementIfAreEqual<string>(
updateNameInRequest,
gotFolderInfo.DisplayName,
5251,
@"[In t:NonEmptyArrayOfFolderChangeDescriptionsType Complex Type]SetFolderField represents an UpdateFolder operation to set a property on an existing folder.");
}
/// <summary>
/// This test case verifies requirements related to updating a folder with AppendToFolderFieldType set.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC02_UpdateFolderWithAppendToFolderFieldType()
{
#region Create a new folder in the inbox folder.
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
FolderIdType folderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
this.NewCreatedFolderIds.Add(folderId);
#endregion
#region Update Folder Operation with AppendToFolderFieldType Complex Type set.
// Specified folder to be updated.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "AppendToFolderField", folderId);
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the length.
Site.Assert.AreEqual<int>(
1,
updateFolderResponse.ResponseMessages.Items.GetLength(0),
"Expected Item Count: {0}, Actual Item Count: {1}",
1,
updateFolderResponse.ResponseMessages.Items.GetLength(0));
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R507");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R507.
Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Error,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
507,
@"[In t:AppendToFolderFieldType Complex Type]Any request that uses this complex type will return an error response.");
#endregion
}
/// <summary>
/// This test case verifies requirements related to updating multiple folders in UpdateFolder operation.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC03_UpdateMultipleFolders()
{
#region Create a new folder in the inbox folder.
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(
DistinguishedFolderIdNameType.inbox.ToString(),
new string[] { "Custom Folder1", "Custom Folder2", "Custom Folder3", "Custom Folder4" },
new string[] { "IPF.Appointment", "IPF.Contact", "IPF.Task", "IPF.Search" },
null);
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 4, this.Site);
FolderIdType folderId1 = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
FolderIdType folderId2 = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[1]).Folders[0].FolderId;
FolderIdType folderId3 = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[2]).Folders[0].FolderId;
FolderIdType folderId4 = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[3]).Folders[0].FolderId;
// Save the new created folder's folder id.
this.NewCreatedFolderIds.Add(folderId1);
this.NewCreatedFolderIds.Add(folderId2);
this.NewCreatedFolderIds.Add(folderId3);
this.NewCreatedFolderIds.Add(folderId4);
#endregion
#region Update Folder Operation.
// UpdateFolder request.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest(
new string[] { "CalendarFolder", "ContactsFolder", "TasksFolder", "SearchFolder" },
new string[] { "SetFolderField", "SetFolderField", "SetFolderField", "SetFolderField" },
new FolderIdType[] { folderId1, folderId2, folderId3, folderId4 });
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the response.
Common.CheckOperationSuccess(updateFolderResponse, 4, this.Site);
#endregion
#region Get the updated folder.
// GetFolder request.
GetFolderType getUpdatedFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folderId1, folderId2, folderId3, folderId4);
// Get the updated folder.
GetFolderResponseType getFolderResponse = this.FOLDAdapter.GetFolder(getUpdatedFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getFolderResponse, 4, this.Site);
FolderInfoResponseMessageType allPropertyOfSearchFolder = (FolderInfoResponseMessageType)getFolderResponse.ResponseMessages.Items[3];
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R33");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R33
this.Site.CaptureRequirementIfIsInstanceOfType(
allPropertyOfSearchFolder.Folders[0],
typeof(SearchFolderType),
33,
@"[In t:ArrayOfFoldersType Complex Type]The type of element SearchFolder is t:SearchFolderType ([MS-OXWSSRCH] section 2.2.3.26).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R3302");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R3302
this.Site.CaptureRequirementIfIsInstanceOfType(
allPropertyOfSearchFolder.Folders[0],
typeof(SearchFolderType),
3302,
@"[In t:ArrayOfFoldersType Complex Type]SearchFolder represents a search folder that is contained in a mailbox.");
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R536");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R536
// Set a property on a CalendarFolderType folder successfully, indicates that Folder represents a regular folder.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
536,
@"[In t:SetFolderFieldType Complex Type]CalendarFolder represents a folder that primarily contains calendar items. ");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R538");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R538
// Set a property on a ContactFolderType folder successfully, indicates that Folder represents a regular folder.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[1].ResponseClass,
538,
@"[In t:SetFolderFieldType Complex Type]ContactsFolder represents a Contacts folder in a mailbox. ");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R542");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R542
// Set a property on a TaskFolderType folder successfully, indicates that Folder represents a regular folder.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[2].ResponseClass,
542,
@"[In t:SetFolderFieldType Complex Type]TasksFolder represents a Tasks folder that is contained in a mailbox. ");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R540");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R540
// Set a property on a SearchFolderType folder successfully, indicates that Folder represents a regular folder.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
updateFolderResponse.ResponseMessages.Items[3].ResponseClass,
540,
@"[In t:SetFolderFieldType Complex Type]SearchFolder represents a search folder that is contained in a mailbox. ");
}
/// <summary>
/// This test case verifies requirements related to UpdateFolder operation via creating a folder and updating it with DeleteFolderFieldType property.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC04_UpdateFolderWithDeleteFolderFieldType()
{
#region Create a new folder in the inbox folder
// Configure permission set.
PermissionSetType permissionSet = new PermissionSetType();
permissionSet.Permissions = new PermissionType[1];
permissionSet.Permissions[0] = new PermissionType();
permissionSet.Permissions[0].CanCreateSubFolders = true;
permissionSet.Permissions[0].CanCreateSubFoldersSpecified = true;
permissionSet.Permissions[0].IsFolderOwner = true;
permissionSet.Permissions[0].IsFolderOwnerSpecified = true;
permissionSet.Permissions[0].PermissionLevel = new PermissionLevelType();
permissionSet.Permissions[0].PermissionLevel = PermissionLevelType.Custom;
permissionSet.Permissions[0].UserId = new UserIdType();
permissionSet.Permissions[0].UserId.PrimarySmtpAddress = Common.GetConfigurationPropertyValue("User2Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site);
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, new PermissionSetType[] { permissionSet });
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
FolderIdType newFolderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
this.NewCreatedFolderIds.Add(newFolderId);
#endregion
#region Update Folder Operation.
// UpdateFolder request to delete folder permission value.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "DeleteFolderField", newFolderId);
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the response.
Common.CheckOperationSuccess(updateFolderResponse, 1, this.Site);
#endregion
#region Switch user
this.SwitchUser(Common.GetConfigurationPropertyValue("User2Name", this.Site), Common.GetConfigurationPropertyValue("User2Password", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site));
#endregion
#region Create a subfolder under the folder created in step 1 with User2's credential
// CreateFolder request.
CreateFolderType createFolderInSharedMailboxRequest = this.GetCreateFolderRequest(newFolderId.Id, new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderInSharedMailboxResponse = this.FOLDAdapter.CreateFolder(createFolderInSharedMailboxRequest);
// Check the length.
Site.Assert.AreEqual<int>(
1,
createFolderInSharedMailboxResponse.ResponseMessages.Items.GetLength(0),
"Expected Item Count: {0}, Actual Item Count: {1}",
1,
createFolderInSharedMailboxResponse.ResponseMessages.Items.GetLength(0));
// Permission have been deleted so create operation should be failed.
bool isPermissionDeleted = createFolderInSharedMailboxResponse.ResponseMessages.Items[0].ResponseClass.Equals(ResponseClassType.Error);
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R583");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R583
// One permission set which set in CreateFolder is deleted when calling UpdateFolder.
this.Site.CaptureRequirementIfIsTrue(
isPermissionDeleted,
583,
@"[In t:DeleteFolderFieldType Complex Type]The DeleteFolderFieldType complex type represents an UpdateFolder operation to delete a property from a folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R5261");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R5261
this.Site.CaptureRequirementIfIsTrue(
isPermissionDeleted,
5261,
@"[In t:NonEmptyArrayOfFolderChangeDescriptionsType Complex Type]DeleteFolderField represents an UpdateFolder operation to delete a property from a folder.");
}
/// <summary>
/// This test case verifies requirement related to ErrorCode of UpdateFolder operation via creating a folder and updating it with multiple properties.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC05_UpdateFolderWithMultipleProperties()
{
#region Create a new folder in the inbox folder.
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
FolderIdType folderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
this.NewCreatedFolderIds.Add(folderId);
#endregion
#region Update Folder Operation.
// UpdateFolder request.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "SetFolderField", folderId);
// In order to verify MS-OXWSCDATA_R335, add another property(PermissionSet) into UpdateFolder request.
FolderType updatingFolder = (FolderType)((SetFolderFieldType)updateFolderRequest.FolderChanges[0].Updates[0]).Item1;
updatingFolder.PermissionSet = new PermissionSetType();
updatingFolder.PermissionSet.Permissions = new PermissionType[1];
updatingFolder.PermissionSet.Permissions[0] = new PermissionType();
updatingFolder.PermissionSet.Permissions[0].CanCreateSubFolders = true;
updatingFolder.PermissionSet.Permissions[0].CanCreateSubFoldersSpecified = true;
updatingFolder.PermissionSet.Permissions[0].IsFolderOwner = true;
updatingFolder.PermissionSet.Permissions[0].IsFolderOwnerSpecified = true;
updatingFolder.PermissionSet.Permissions[0].PermissionLevel = new PermissionLevelType();
updatingFolder.PermissionSet.Permissions[0].PermissionLevel = PermissionLevelType.Custom;
updatingFolder.PermissionSet.Permissions[0].UserId = new UserIdType();
updatingFolder.PermissionSet.Permissions[0].UserId.PrimarySmtpAddress = Common.GetConfigurationPropertyValue("User2Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site);
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the length.
Site.Assert.AreEqual<int>(
1,
updateFolderResponse.ResponseMessages.Items.GetLength(0),
"Expected Item Count: {0}, Actual Item Count: {1}",
1,
updateFolderResponse.ResponseMessages.Items.GetLength(0));
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSCDATA_R335");
// Verify MS-OXWSCDATA requirement: MS-OXWSCDATA_R335
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.ErrorIncorrectUpdatePropertyCount,
updateFolderResponse.ResponseMessages.Items[0].ResponseCode,
"MS-OXWSCDATA",
335,
@"[In m:ResponseCodeType Simple Type] The value ""ErrorIncorrectUpdatePropertyCount"" specifies that each change description in an UpdateItem or UpdateFolder method call MUST list only one property to be updated.");
#endregion
}
/// <summary>
/// This test case verifies requirements related to UpdateFolder operation via updating a distinguished folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC06_UpdateDistinguishedFolder()
{
#region Get the sent items folder.
DistinguishedFolderIdType folderId = new DistinguishedFolderIdType();
folderId.Id = DistinguishedFolderIdNameType.sentitems;
// GetFolder request.
GetFolderType getSentItemsFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folderId);
GetFolderResponseType getSentItemsFolderResponse = this.FOLDAdapter.GetFolder(getSentItemsFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getSentItemsFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getSentItemsFolderResponse.ResponseMessages.Items[0];
BaseFolderType folderInfo = (BaseFolderType)allFolders.Folders[0];
#endregion
#region Update Folder Operation.
// UpdateFolder request to delete folder permission value.
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "DeleteFolderField", folderInfo.FolderId);
// Set change key value.
folderId.ChangeKey = folderInfo.FolderId.ChangeKey;
updateFolderRequest.FolderChanges[0].Item = folderId;
// Update the specific folder's properties.
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Check the response.
Common.CheckOperationSuccess(updateFolderResponse, 1, this.Site);
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R9101");
// Distinguished folder id set and update folder return a successfully, this requirement can be captured.
this.Site.CaptureRequirement(
9101,
@"[In t:FolderChangeType Complex Type]DistinguishedFolderId specifies an identifier for a distinguished folder.");
}
/// <summary>
/// This test case verifies requirements related to update folder failed.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S06_TC07_UpdateFolderFailed()
{
#region Create a new folder in the inbox folder
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
FolderIdType newFolderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
this.NewCreatedFolderIds.Add(newFolderId);
#endregion
#region Delete the created folder
// DeleteFolder request.
DeleteFolderType deleteFolderRequest = this.GetDeleteFolderRequest(DisposalType.HardDelete, newFolderId);
// Delete the specified folder.
DeleteFolderResponseType deleteFolderResponse = this.FOLDAdapter.DeleteFolder(deleteFolderRequest);
// Check the response.
Common.CheckOperationSuccess(deleteFolderResponse, 1, this.Site);
// The folder has been deleted, so its folder id has disappeared.
this.NewCreatedFolderIds.Remove(newFolderId);
#endregion
#region Move the deleted folder
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest("Folder", "SetFolderField", newFolderId);
UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest);
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R4645");
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Error,
updateFolderResponse.ResponseMessages.Items[0].ResponseClass,
4645,
@"[In UpdateFolder Operation]An unsuccessful UpdateFolder operation request returns an UpdateFolderResponse element with the ResponseClass attribute of the UpdateFolderResponseMessage element set to ""Error"".");
#endregion
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace StreamTests
{
public class StringWriterTests
{
static int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue };
static int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 };
static int[] iArrValidValues = new Int32[] { 10000, 100000, Int32.MaxValue / 2000, Int32.MaxValue / 5000, Int16.MaxValue };
private static char[] getCharArray()
{
return new char[]{
Char.MinValue
,Char.MaxValue
,'\t'
,' '
,'$'
,'@'
,'#'
,'\0'
,'\v'
,'\''
,'\u3190'
,'\uC3A0'
,'A'
,'5'
,'\uFE70'
,'-'
,';'
,'\u00E6'
};
}
private static StringBuilder getSb()
{
var chArr = getCharArray();
var sb = new StringBuilder(40);
for (int i = 0; i < chArr.Length; i++)
sb.Append(chArr[i]);
return sb;
}
[Fact]
public static void Ctor()
{
StringWriter sw = new StringWriter();
Assert.NotNull(sw);
}
[Fact]
public static void CtorWithStringBuilder()
{
var sb = getSb();
StringWriter sw = new StringWriter(getSb());
Assert.NotNull(sw);
Assert.Equal(sb.Length, sw.GetStringBuilder().Length);
}
[Fact]
public static void CtorWithCultureInfo()
{
StringWriter sw = new StringWriter(new CultureInfo("en-gb"));
Assert.NotNull(sw);
Assert.Equal(new CultureInfo("en-gb"), sw.FormatProvider);
}
[Fact]
public static void SimpleWriter()
{
var sw = new StringWriter();
sw.Write(4);
var sb = sw.GetStringBuilder();
Assert.Equal("4", sb.ToString());
}
[Fact]
public static void WriteArray()
{
var chArr = getCharArray();
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
var sr = new StringReader(sw.GetStringBuilder().ToString());
for (int i = 0; i < chArr.Length; i++)
{
int tmp = sr.Read();
Assert.Equal((int)chArr[i], tmp);
}
}
[Fact]
public static void CantWriteNullArray()
{
var sw = new StringWriter();
Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0));
}
[Fact]
public static void CantWriteNegativeOffset()
{
var sw = new StringWriter();
Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], -1, 0));
}
[Fact]
public static void CantWriteNegativeCount()
{
var sw = new StringWriter();
Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], 0, -1));
}
[Fact]
public static void CantWriteIndexLargeValues()
{
var chArr = getCharArray();
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
Assert.Throws<ArgumentException>(() => sw.Write(chArr, iArrLargeValues[i], chArr.Length));
}
}
[Fact]
public static void CantWriteCountLargeValues()
{
var chArr = getCharArray();
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
Assert.Throws<ArgumentException>(() => sw.Write(chArr, 0, iArrLargeValues[i]));
}
}
[Fact]
public static void WriteWithOffset()
{
StringWriter sw = new StringWriter();
StringReader sr;
var chArr = getCharArray();
sw.Write(chArr, 2, 5);
sr = new StringReader(sw.ToString());
for (int i = 2; i < 7; i++)
{
int tmp = sr.Read();
Assert.Equal((int)chArr[i], tmp);
}
}
[Fact]
public static void WriteWithLargeIndex()
{
for (int i = 0; i < iArrValidValues.Length; i++)
{
StringBuilder sb = new StringBuilder(Int32.MaxValue / 2000);
StringWriter sw = new StringWriter(sb);
var chArr = new Char[Int32.MaxValue / 2000];
for (int j = 0; j < chArr.Length; j++)
chArr[j] = (char)(j % 256);
sw.Write(chArr, iArrValidValues[i] - 1, 1);
String strTemp = sw.GetStringBuilder().ToString();
Assert.Equal(1, strTemp.Length);
}
}
[Fact]
public static void WriteWithLargeCount()
{
for (int i = 0; i < iArrValidValues.Length; i++)
{
StringBuilder sb = new StringBuilder(Int32.MaxValue / 2000);
StringWriter sw = new StringWriter(sb);
var chArr = new Char[Int32.MaxValue / 2000];
for (int j = 0; j < chArr.Length; j++)
chArr[j] = (char)(j % 256);
sw.Write(chArr, 0, iArrValidValues[i]);
String strTemp = sw.GetStringBuilder().ToString();
Assert.Equal(iArrValidValues[i], strTemp.Length);
}
}
[Fact]
public static void NewStringWriterIsEmpty()
{
var sw = new StringWriter();
Assert.Equal(String.Empty, sw.ToString());
}
[Fact]
public static void NewStringWriterHasEmptyStringBuilder()
{
var sw = new StringWriter();
Assert.Equal(String.Empty, sw.GetStringBuilder().ToString());
}
[Fact]
public static void ToStringReturnsWrittenData()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
Assert.Equal(sb.ToString(), sw.ToString());
}
[Fact]
public static void StringBuilderHasCorrectData()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString());
}
[Fact]
public static void Disposed()
{
StringWriter sw = new StringWriter();
sw.Dispose();
}
[Fact]
public static async Task FlushAsyncWorks()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
await sw.FlushAsync(); // I think this is a noop in this case
Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString());
}
[Fact]
public static void MiscWrites()
{
var sw = new StringWriter();
sw.Write('H');
sw.Write("ello World!");
Assert.Equal("Hello World!", sw.ToString());
}
[Fact]
public static async Task MiscWritesAsync()
{
var sw = new StringWriter();
await sw.WriteAsync('H');
await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' });
await sw.WriteAsync("World!");
Assert.Equal("Hello World!", sw.ToString());
}
[Fact]
public static async Task MiscWriteLineAsync()
{
var sw = new StringWriter();
await sw.WriteLineAsync('H');
await sw.WriteLineAsync(new char[] { 'e', 'l', 'l', 'o' });
await sw.WriteLineAsync("World!");
Assert.Equal(
string.Format("H{0}ello{0}World!{0}", Environment.NewLine),
sw.ToString());
}
[Fact]
public static void GetEncoding()
{
var sw = new StringWriter();
Assert.Equal(Encoding.Unicode.WebName, sw.Encoding.WebName);
}
[Fact]
public static void TestWriteMisc()
{
CultureInfo old = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
try
{
var sw = new StringWriter();
sw.Write(true);
sw.Write((char)'a');
sw.Write(new Decimal(1234.01));
sw.Write((double)3452342.01);
sw.Write((int)23456);
sw.Write((long)long.MinValue);
sw.Write((float)1234.50f);
sw.Write((UInt32)UInt32.MaxValue);
sw.Write((UInt64)UInt64.MaxValue);
Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString());
}
finally
{
CultureInfo.CurrentCulture = old;
}
}
[Fact]
public static void TestWriteObject()
{
var sw = new StringWriter();
sw.Write(new Object());
Assert.Equal("System.Object", sw.ToString());
}
[Fact]
public static void TestWriteLineMisc()
{
CultureInfo old = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
try
{
var sw = new StringWriter();
sw.WriteLine((bool)false);
sw.WriteLine((char)'B');
sw.WriteLine((int)987);
sw.WriteLine((long)875634);
sw.WriteLine((Single)1.23457f);
sw.WriteLine((UInt32)45634563);
sw.WriteLine((UInt64.MaxValue));
Assert.Equal(
string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine),
sw.ToString());
}
finally
{
CultureInfo.CurrentCulture = old;
}
}
[Fact]
public static void TestWriteLineObject()
{
var sw = new StringWriter();
sw.WriteLine(new Object());
Assert.Equal("System.Object" + Environment.NewLine, sw.ToString());
}
[Fact]
public static void TestWriteLineAsyncCharArray()
{
StringWriter sw = new StringWriter();
sw.WriteLineAsync(new char[] { 'H', 'e', 'l', 'l', 'o' });
Assert.Equal("Hello" + Environment.NewLine, sw.ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace HardwhereApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripRenderer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms.Internal;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Windows.Forms.Layout;
using System.Security;
using System.Security.Permissions;
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer"]/*' />
public abstract class ToolStripRenderer {
private static readonly object EventRenderSplitButtonBackground = new object();
private static readonly object EventRenderItemBackground = new object();
private static readonly object EventRenderItemImage = new object();
private static readonly object EventRenderItemText = new object();
private static readonly object EventRenderToolStripBackground = new object();
private static readonly object EventRenderGrip = new object();
private static readonly object EventRenderButtonBackground = new object();
private static readonly object EventRenderLabelBackground = new object();
private static readonly object EventRenderMenuItemBackground = new object();
private static readonly object EventRenderDropDownButtonBackground = new object();
private static readonly object EventRenderOverflowButtonBackground = new object();
private static readonly object EventRenderImageMargin = new object();
private static readonly object EventRenderBorder = new object();
private static readonly object EventRenderArrow = new object();
private static readonly object EventRenderStatusStripPanelBackground = new object();
private static readonly object EventRenderToolStripStatusLabelBackground = new object();
private static readonly object EventRenderSeparator = new object();
private static readonly object EventRenderItemCheck = new object();
private static readonly object EventRenderToolStripPanelBackground = new object();
private static readonly object EventRenderToolStripContentPanelBackground = new object();
private static readonly object EventRenderStatusStripSizingGrip = new object();
private static ColorMatrix disabledImageColorMatrix;
private EventHandlerList events;
private bool isAutoGenerated = false;
private static bool isScalingInitialized = false;
// arrows are rendered as isosceles triangles, whose heights are half the base in order to have 45 degree angles
// Offset2X is half of the base
// Offset2Y is height of the isosceles triangle
private static int OFFSET_2PIXELS = 2;
private static int OFFSET_4PIXELS = 4;
protected static int Offset2X = OFFSET_2PIXELS;
protected static int Offset2Y = OFFSET_2PIXELS;
private static int offset4Y = OFFSET_4PIXELS;
// this is used in building up the half pyramid of rectangles that are drawn in a
// status strip sizing grip.
private static Rectangle[] baseSizeGripRectangles = new Rectangle[] { new Rectangle(8,0,2,2),
new Rectangle(8,4,2,2),
new Rectangle(8,8,2,2),
new Rectangle(4,4,2,2),
new Rectangle(4,8,2,2),
new Rectangle(0,8,2,2) };
protected ToolStripRenderer() {
}
internal ToolStripRenderer(bool isAutoGenerated) {
this.isAutoGenerated = isAutoGenerated;
}
// this is used in building disabled images.
private static ColorMatrix DisabledImageColorMatrix {
get {
if (disabledImageColorMatrix == null) {
// VSWhidbey 233470
// this is the result of a GreyScale matrix multiplied by a transparency matrix of .5
float[][] greyscale = new float[5][];
greyscale[0] = new float[5] {0.2125f, 0.2125f, 0.2125f, 0, 0};
greyscale[1] = new float[5] {0.2577f, 0.2577f, 0.2577f, 0, 0};
greyscale[2] = new float[5] {0.0361f, 0.0361f, 0.0361f, 0, 0};
greyscale[3] = new float[5] {0, 0, 0, 1, 0};
greyscale[4] = new float[5] {0.38f, 0.38f, 0.38f, 0, 1};
float[][] transparency = new float[5][];
transparency[0] = new float[5] {1, 0, 0, 0, 0};
transparency[1] = new float[5] {0, 1, 0, 0, 0};
transparency[2] = new float[5] {0, 0, 1, 0, 0};
transparency[3] = new float[5] {0, 0, 0, .7F, 0};
transparency[4] = new float[5] {0, 0, 0, 0, 0};
disabledImageColorMatrix = ControlPaint.MultiplyColorMatrix(transparency, greyscale);
}
return disabledImageColorMatrix;
}
}
/// <devdoc>
/// <para>Gets the list of event handlers that are attached to this component.</para>
/// </devdoc>
private EventHandlerList Events {
get {
if (events == null) {
events = new EventHandlerList();
}
return events;
}
}
internal bool IsAutoGenerated {
get { return isAutoGenerated; }
}
// if we're in a low contrast, high resolution situation, use this renderer under the covers instead.
internal virtual ToolStripRenderer RendererOverride {
get {
return null;
}
}
/// -----------------------------------------------------------------------------
/// SECREVIEW VSWhidbey 250785 - all stock renderer events require AllWindowsPermission
/// use the private AddHandler/RemoveHandler to ensure that security checks are
/// made.
/// -----------------------------------------------------------------------------
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderArrow"]/*' />
public event ToolStripArrowRenderEventHandler RenderArrow {
add {
AddHandler(EventRenderArrow, value);
}
remove {
RemoveHandler(EventRenderArrow, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderToolStripBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderToolStripBackground {
add {
AddHandler(EventRenderToolStripBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripBackground, value);
}
}
public event ToolStripPanelRenderEventHandler RenderToolStripPanelBackground {
add {
AddHandler(EventRenderToolStripPanelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripPanelBackground, value);
}
}
public event ToolStripContentPanelRenderEventHandler RenderToolStripContentPanelBackground {
add {
AddHandler(EventRenderToolStripContentPanelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripContentPanelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderBorder"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderToolStripBorder {
add {
AddHandler(EventRenderBorder, value);
}
remove {
RemoveHandler(EventRenderBorder, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderButtonBackground {
add {
AddHandler(EventRenderButtonBackground, value);
}
remove {
RemoveHandler(EventRenderButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderDropDownButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderDropDownButtonBackground {
add {
AddHandler(EventRenderDropDownButtonBackground, value);
}
remove {
RemoveHandler(EventRenderDropDownButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderOverflowButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderOverflowButtonBackground {
add {
AddHandler(EventRenderOverflowButtonBackground, value);
}
remove {
RemoveHandler(EventRenderOverflowButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderGrip"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripGripRenderEventHandler RenderGrip {
add {
AddHandler(EventRenderGrip, value);
}
remove {
RemoveHandler(EventRenderGrip, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItem"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderItemBackground {
add {
AddHandler(EventRenderItemBackground, value);
}
remove {
RemoveHandler(EventRenderItemBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemImage"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemImageRenderEventHandler RenderItemImage {
add {
AddHandler(EventRenderItemImage, value);
}
remove {
RemoveHandler(EventRenderItemImage, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemCheck"]/*' />
/// <devdoc>
/// Draws the checkmark
/// </devdoc>
public event ToolStripItemImageRenderEventHandler RenderItemCheck {
add {
AddHandler(EventRenderItemCheck, value);
}
remove {
RemoveHandler(EventRenderItemCheck, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemText"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemTextRenderEventHandler RenderItemText {
add {
AddHandler(EventRenderItemText, value);
}
remove {
RemoveHandler(EventRenderItemText, value);
}
}
public event ToolStripRenderEventHandler RenderImageMargin {
add {
AddHandler(EventRenderImageMargin, value);
}
remove {
RemoveHandler(EventRenderImageMargin, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderLabelBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderLabelBackground {
add {
AddHandler(EventRenderLabelBackground, value);
}
remove {
RemoveHandler(EventRenderLabelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderMenuItemBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderMenuItemBackground {
add {
AddHandler(EventRenderMenuItemBackground, value);
}
remove {
RemoveHandler(EventRenderMenuItemBackground, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderStatusStripPanelBackground"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderToolStripStatusLabelBackground {
add {
AddHandler(EventRenderToolStripStatusLabelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripStatusLabelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderToolStripBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderStatusStripSizingGrip {
add {
AddHandler(EventRenderStatusStripSizingGrip, value);
}
remove {
RemoveHandler(EventRenderStatusStripSizingGrip, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderSplitButtonBackground"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderSplitButtonBackground {
add {
AddHandler(EventRenderSplitButtonBackground, value);
}
remove {
RemoveHandler(EventRenderSplitButtonBackground, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderSeparator"]/*' />
public event ToolStripSeparatorRenderEventHandler RenderSeparator {
add {
AddHandler(EventRenderSeparator, value);
}
remove {
RemoveHandler(EventRenderSeparator, value);
}
}
#region EventHandlerSecurity
/// -----------------------------------------------------------------------------
/// SECREVIEW VSWhidbey 250785 - all stock renderer events require AllWindowsPermission
/// use the private AddHandler/RemoveHandler to ensure that security checks are
/// made.
/// -----------------------------------------------------------------------------
[UIPermission(SecurityAction.Demand, Window=UIPermissionWindow.AllWindows)]
private void AddHandler(object key, Delegate value) {
Events.AddHandler(key, value);
}
[UIPermission(SecurityAction.Demand, Window=UIPermissionWindow.AllWindows)]
private void RemoveHandler(object key, Delegate value) {
Events.RemoveHandler(key, value);
}
#endregion
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.CreateDisabledImage"]/*' />
public static Image CreateDisabledImage(Image normalImage) {
ImageAttributes imgAttrib = new ImageAttributes();
imgAttrib.ClearColorKey();
imgAttrib.SetColorMatrix(DisabledImageColorMatrix);
Size size = normalImage.Size;
Bitmap disabledBitmap = new Bitmap(size.Width, size.Height);
Graphics graphics = Graphics.FromImage(disabledBitmap);
graphics.DrawImage(normalImage,
new Rectangle(0, 0, size.Width, size.Height),
0, 0, size.Width, size.Height,
GraphicsUnit.Pixel,
imgAttrib);
graphics.Dispose();
return disabledBitmap;
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawArrow"]/*' />
public void DrawArrow(ToolStripArrowRenderEventArgs e) {
OnRenderArrow(e);
ToolStripArrowRenderEventHandler eh = Events[EventRenderArrow] as ToolStripArrowRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawBackground"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawToolStripBackground(ToolStripRenderEventArgs e) {
OnRenderToolStripBackground(e);
ToolStripRenderEventHandler eh = Events[EventRenderToolStripBackground] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawGrip"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawGrip(ToolStripGripRenderEventArgs e) {
OnRenderGrip(e);
ToolStripGripRenderEventHandler eh = Events[EventRenderGrip] as ToolStripGripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItem"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawItemBackground(ToolStripItemRenderEventArgs e)
{
OnRenderItemBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderItemBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawImageMargin"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawImageMargin(ToolStripRenderEventArgs e) {
OnRenderImageMargin(e);
ToolStripRenderEventHandler eh = Events[EventRenderImageMargin] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawLabel"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawLabelBackground(ToolStripItemRenderEventArgs e)
{
OnRenderLabelBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderLabelBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawBorder"]/*' />
public void DrawToolStripBorder(ToolStripRenderEventArgs e)
{
OnRenderToolStripBorder(e);
ToolStripRenderEventHandler eh = Events[EventRenderBorder] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawDropDownButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawDropDownButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderDropDownButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderDropDownButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawOverflowButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderOverflowButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderOverflowButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemImage"]/*' />
/// <devdoc>
/// Draw image
/// </devdoc>
public void DrawItemImage(ToolStripItemImageRenderEventArgs e) {
OnRenderItemImage(e);
ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemImage] as ToolStripItemImageRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemCheck"]/*' />
/// <devdoc>
/// Draw image
/// </devdoc>
public void DrawItemCheck(ToolStripItemImageRenderEventArgs e) {
OnRenderItemCheck(e);
ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemCheck] as ToolStripItemImageRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemText"]/*' />
/// <devdoc>
/// Draw text
/// </devdoc>
public void DrawItemText(ToolStripItemTextRenderEventArgs e) {
OnRenderItemText(e);
ToolStripItemTextRenderEventHandler eh = Events[EventRenderItemText] as ToolStripItemTextRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawMenuItem"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawMenuItemBackground(ToolStripItemRenderEventArgs e)
{
OnRenderMenuItemBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderMenuItemBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawSplitButton"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawSplitButton(ToolStripItemRenderEventArgs e) {
OnRenderSplitButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderSplitButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawToolStripStatusLabel"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) {
OnRenderToolStripStatusLabelBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderToolStripStatusLabelBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
//
public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) {
OnRenderStatusStripSizingGrip(e);
ToolStripRenderEventHandler eh = Events[EventRenderStatusStripSizingGrip] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawSeparator"]/*' />
/// <devdoc>
/// Draw the separator
/// </devdoc>
public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) {
OnRenderSeparator(e);
ToolStripSeparatorRenderEventHandler eh = Events[EventRenderSeparator] as ToolStripSeparatorRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) {
OnRenderToolStripPanelBackground(e);
ToolStripPanelRenderEventHandler eh = Events[EventRenderToolStripPanelBackground] as ToolStripPanelRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
public void DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) {
OnRenderToolStripContentPanelBackground(e);
ToolStripContentPanelRenderEventHandler eh = Events[EventRenderToolStripContentPanelBackground] as ToolStripContentPanelRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
// consider make public
internal virtual Region GetTransparentRegion(ToolStrip toolStrip) {
return null;
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void Initialize(ToolStrip toolStrip){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void InitializePanel(ToolStripPanel toolStripPanel){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void InitializeContentPanel(ToolStripContentPanel contentPanel){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.InitializeItem"]/*' />
protected internal virtual void InitializeItem (ToolStripItem item){
}
protected static void ScaleArrowOffsetsIfNeeded() {
if (isScalingInitialized) {
return;
}
if (DpiHelper.IsScalingRequired) {
Offset2X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_2PIXELS);
Offset2Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_2PIXELS);
offset4Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_4PIXELS);
}
isScalingInitialized = true;
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderArrow"]/*' />
protected virtual void OnRenderArrow(ToolStripArrowRenderEventArgs e){
if (RendererOverride != null) {
RendererOverride.OnRenderArrow(e);
return;
}
Graphics g = e.Graphics;
Rectangle dropDownRect = e.ArrowRectangle;
using (Brush brush = new SolidBrush(e.ArrowColor)) {
Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2);
// if the width is odd - favor pushing it over one pixel right.
//middle.X += (dropDownRect.Width % 2);
Point[] arrow = null;
ScaleArrowOffsetsIfNeeded();
switch (e.Direction) {
case ArrowDirection.Up:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y + 1),
new Point(middle.X + Offset2X + 1, middle.Y + 1),
new Point(middle.X, middle.Y - Offset2Y)};
break;
case ArrowDirection.Left:
arrow = new Point[] {
new Point(middle.X + Offset2X, middle.Y - offset4Y),
new Point(middle.X + Offset2X, middle.Y + offset4Y),
new Point(middle.X - Offset2X, middle.Y)};
break;
case ArrowDirection.Right:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y - offset4Y),
new Point(middle.X - Offset2X, middle.Y + offset4Y),
new Point(middle.X + Offset2X, middle.Y)};
break;
case ArrowDirection.Down:
default:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y - 1),
new Point(middle.X + Offset2X + 1, middle.Y - 1),
new Point(middle.X, middle.Y + Offset2Y) };
break;
}
g.FillPolygon(brush, arrow);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderToolStripBackground"]/*' />
/// <devdoc>
/// Draw the winbar background. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected virtual void OnRenderToolStripBackground(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderBorder"]/*' />
/// <devdoc>
/// Draw the border around the ToolStrip. This should be done as the last step.
/// </devdoc>
protected virtual void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripBorder(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderGrip"]/*' />
/// <devdoc>
/// Draw the grip. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected virtual void OnRenderGrip(ToolStripGripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderGrip(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItem"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderItemBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderImageMargin"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderImageMargin(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderImageMargin(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderDropDownButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderDropDownButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderOverflowButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderOverflowButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemImage"]/*' />
/// <devdoc>
/// Draw the item'si mage. ToolStrip users should override this function to change the
/// drawing of all images.
/// </devdoc>
protected virtual void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemImage(e);
return;
}
Rectangle imageRect = e.ImageRectangle;
Image image = e.Image;
if (imageRect != Rectangle.Empty && image != null) {
bool disposeImage = false;
if (e.ShiftOnPress && e.Item.Pressed) {
imageRect.X +=1;
}
if (!e.Item.Enabled) {
image = CreateDisabledImage(image);
disposeImage = true;
}
if (e.Item.ImageScaling == ToolStripItemImageScaling.None) {
e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty,imageRect.Size), GraphicsUnit.Pixel);
}
else {
e.Graphics.DrawImage(image, imageRect);
}
if (disposeImage) {
image.Dispose();
}
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemCheck"]/*' />
protected virtual void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemCheck(e);
return;
}
Rectangle imageRect = e.ImageRectangle;
Image image = e.Image;
if (imageRect != Rectangle.Empty && image != null) {
if (!e.Item.Enabled) {
image = CreateDisabledImage(image);
}
e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty,imageRect.Size), GraphicsUnit.Pixel);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemText"]/*' />
/// <devdoc>
/// Draw the item's text. ToolStrip users should override this function to change the
/// drawing of all text.
/// </devdoc>
protected virtual void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemText(e);
return;
}
ToolStripItem item = e.Item;
Graphics g = e.Graphics;
Color textColor = e.TextColor;
Font textFont = e.TextFont;
string text = e.Text;
Rectangle textRect = e.TextRectangle;
TextFormatFlags textFormat = e.TextFormat;
// if we're disabled draw in a different color.
textColor = (item.Enabled) ? textColor : SystemColors.GrayText;
if (e.TextDirection != ToolStripTextDirection.Horizontal && textRect.Width > 0 && textRect.Height > 0) {
// Perf: this is a bit heavy handed.. perhaps we can share the bitmap.
Size textSize = LayoutUtils.FlipSize(textRect.Size);
using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height,PixelFormat.Format32bppPArgb)) {
using (Graphics textGraphics = Graphics.FromImage(textBmp)) {
// now draw the text..
textGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
TextRenderer.DrawText(textGraphics, text, textFont, new Rectangle(Point.Empty, textSize), textColor, textFormat);
textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
g.DrawImage(textBmp, textRect);
}
}
}
else {
TextRenderer.DrawText(g, text, textFont, textRect, textColor, textFormat);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderLabelBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderLabelBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderMenuItemBackground"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderMenuItemBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSeparator"]/*' />
/// <devdoc>
/// Draws a toolbar separator. ToolStrip users should override this function to change the
/// drawing of all separators.
/// </devdoc>
protected virtual void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderSeparator(e);
return;
}
}
protected virtual void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripPanelBackground(e);
return;
}
}
protected virtual void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripContentPanelBackground(e);
return;
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderStatusStripPanelBackground"]/*' />
protected virtual void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripStatusLabelBackground(e);
return;
}
}
protected virtual void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderStatusStripSizingGrip(e);
return;
}
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*/);
whiteRectangles[i] = baseRect;
if (statusStrip.RightToLeft == RightToLeft.Yes) {
baseRect.Offset(1, -1);
}
else {
baseRect.Offset(-1, -1);
}
greyRectangles[i] = baseRect;
}
g.FillRectangles(SystemBrushes.ButtonHighlight, whiteRectangles);
g.FillRectangles(SystemBrushes.ButtonShadow, greyRectangles);
}
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSplitButtonBackground"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
protected virtual void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderSplitButtonBackground(e);
return;
}
}
// VSWhidbey 252459: only paint background effects if no backcolor has been set or no background image has been set.
internal bool ShouldPaintBackground (Control control) {
return (control.RawBackColor == Color.Empty && control.BackgroundImage == null);
}
}
}
| |
//#define PROFILE
//#define DBG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.Types;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.Drawers
{
public class IDictionaryDrawer<TK, TV> : ObjectDrawer<IDictionary<TK, TV>>
{
private EditorMember _tempKeyMember;
private List<EditorMember> _keyElements, _valueElements;
private KVPList<TK, TV> _kvpList;
private Attribute[] _perKeyAttributes, _perValueAttributes;
private DictionaryOptions _options;
private string _formatPairPattern;
private bool _invalidKeyType;
private TextFilter _filter;
private string _originalDisplay;
private int _lastUpdatedCount = -1;
private TK _tempKey;
public bool UpdateCount = true;
protected override void Initialize()
{
_invalidKeyType = !typeof(TK).IsValueType && typeof(TK) != typeof(string);
if (_invalidKeyType)
return;
_keyElements = new List<EditorMember>();
_valueElements = new List<EditorMember>();
var perKey = attributes.GetAttribute<PerKeyAttribute>();
if (perKey != null)
{
if (perKey.ExplicitAttributes == null)
_perKeyAttributes = attributes.Where(x => !(x is PerKeyAttribute)).ToArray();
else _perKeyAttributes = attributes.Where(x => perKey.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray();
}
var perValue = attributes.GetAttribute<PerValueAttribute>();
if (perValue != null)
{
if (perValue.ExplicitAttributes == null)
_perValueAttributes = attributes.Where(x => !(x is PerValueAttribute)).ToArray();
else _perValueAttributes = attributes.Where(x => perValue.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray();
}
var displayAttr = attributes.GetAttribute<DisplayAttribute>();
if (displayAttr != null)
_formatPairPattern = displayAttr.FormatKVPair;
_options = new DictionaryOptions(displayAttr != null ? displayAttr.DictOpt : Dict.None);
if (_formatPairPattern.IsNullOrEmpty())
_formatPairPattern = "[$key, $value]";
if (_options.Readonly)
displayText += " (Readonly)";
_originalDisplay = displayText;
if (_options.Filter)
_filter = new TextFilter(null, id, true, prefs, null);
if (memberValue == null && !_options.ManualAlloc)
memberValue = memberType.Instance<IDictionary<TK, TV>>();
if (memberValue != null)
member.CollectionCount = memberValue.Count;
if (_options.TempKey)
{
_tempKeyMember = EditorMember.WrapMember(GetType().GetField("_tempKey", Flags.InstanceAnyVisibility),
this, unityTarget, RuntimeHelper.CombineHashCodes(id, "temp"), null);
_tempKeyMember.DisplayText = string.Empty;
_tempKey = GetNewKey(memberValue);
}
#if DBG
Log("Dictionary drawer Initialized (" + dictionaryName + ")");
#endif
}
public override void OnGUI()
{
if (_invalidKeyType)
{
gui.HelpBox("Unsuported key type: {0}. Only Value-types and strings are, sorry!"
.FormatWith(typeof(TK)), MessageType.Error);
return;
}
if (memberValue == null)
{
if (_options.ManualAlloc)
{
using(gui.Horizontal())
{
gui.Label(member.NiceName + " (Null)");
if (gui.Button("New", GUIStyles.MiniRight, Layout.sFit()))
memberValue = memberType.Instance<IDictionary<TK, TV>>();
}
}
else memberValue = memberType.Instance<IDictionary<TK, TV>>();
}
if (memberValue == null)
return;
member.CollectionCount = memberValue.Count;
if (UpdateCount && _lastUpdatedCount != memberValue.Count)
{
_lastUpdatedCount = memberValue.Count;
displayText = Regex.Replace(_originalDisplay, @"\$count", _lastUpdatedCount.ToString());
}
if (_kvpList == null)
_kvpList = new KVPList<TK, TV>();
else _kvpList.Clear();
// Read
{
var iter = memberValue.GetEnumerator();
while(iter.MoveNext())
{
var key = iter.Current.Key;
var value = iter.Current.Value;
_kvpList[key] = value;
}
}
#if PROFILE
Profiler.BeginSample("DictionaryDrawer Header");
#endif
// header
if (!_options.HideHeader)
{
using (gui.Horizontal())
{
if (_options.ForceExpand)
gui.Label(displayText);
else
foldout = gui.Foldout(displayText, foldout, Layout.Auto);
if (_options.Filter)
_filter.Field(gui, 70f);
if (!_options.Readonly)
{
if (_options.TempKey)
{
string controlName = "TempKey";
GUI.SetNextControlName(controlName);
gui.Member(_tempKeyMember);
var e = Event.current;
if (e.type == EventType.KeyUp && e.keyCode == KeyCode.Return && GUI.GetNameOfFocusedControl() == controlName)
{
AddNewPair();
EditorGUI.FocusTextInControl(controlName);
}
}
else gui.FlexibleSpace();
if (!_options.HideButtons)
{
using (gui.State(_kvpList.Count > 0))
{
if (gui.ClearButton("dictionary"))
_kvpList.Clear();
if (gui.RemoveButton("last added dictionary pair"))
{
if (_options.AddToLast)
_kvpList.RemoveLast();
else
_kvpList.RemoveFirst();
}
}
if (gui.AddButton("pair", MiniButtonStyle.ModRight))
AddNewPair();
}
}
}
gui.Space(3f);
}
#if PROFILE
Profiler.EndSample();
#endif
if (!foldout && !_options.ForceExpand)
return;
if (memberValue.Count == 0)
{
using (gui.Indent())
gui.HelpBox("Dictionary is empty");
}
else
{
#if PROFILE
Profiler.BeginSample("DictionaryDrawer Pairs");
#endif
using (gui.Indent())
{
for (int i = 0; i < _kvpList.Count; i++)
{
var dKey = _kvpList.Keys[i];
var dValue = _kvpList.Values[i];
#if PROFILE
Profiler.BeginSample("DictionaryDrawer KVP assignments");
#endif
int entryKey = RuntimeHelper.CombineHashCodes(id, i, "entry");
string pairStr = null;
if (_filter != null)
{
pairStr = FormatPair(dKey, dValue);
#if PROFILE
Profiler.BeginSample("DictionaryDrawer Filter");
#endif
bool match = _filter.IsMatch(pairStr);
#if PROFILE
Profiler.EndSample();
#endif
if (!match)
continue;
}
if (!_options.HorizontalPairs)
{
if (pairStr == null)
pairStr = FormatPair(dKey, dValue);
prefs[entryKey] = gui.Foldout(pairStr, prefs[entryKey], Layout.Auto);
}
#if PROFILE
Profiler.EndSample();
#endif
if (!prefs[entryKey] && !_options.HorizontalPairs)
continue;
#if PROFILE
Profiler.BeginSample("DictionaryDrawer SinglePair");
#endif
if (_options.HorizontalPairs)
{
using (gui.Horizontal())
{
DrawKey(i, entryKey + 1);
DrawValue(i, entryKey + 2);
}
}
else
{
using (gui.Indent())
{
DrawKey(i, entryKey + 1);
DrawValue(i, entryKey + 2);
}
}
#if PROFILE
Profiler.EndSample();
#endif
}
}
#if PROFILE
Profiler.EndSample();
#endif
#if PROFILE
Profiler.BeginSample("DictionaryDrawer Write");
#endif
// Write
{
Write();
}
#if PROFILE
Profiler.EndSample();
#endif
}
}
private void Write()
{
memberValue.Clear();
for (int i = 0; i < _kvpList.Count; i++)
{
var key = _kvpList.Keys[i];
var value = _kvpList.Values[i];
try
{
memberValue.Add(key, value);
}
catch (ArgumentException) //@Todo: figure out a more forgiveful way to handle this
{
Log("Key already exists: " + key);
}
}
}
public void DrawKey(int index, int id)
{
var keyMember = GetElement(_keyElements, _kvpList.Keys, index, id + 1);
using(gui.If(!_options.Readonly && typeof(TK).IsNumeric(), gui.LabelWidth(15f)))
{
if (_options.Readonly)
{
var previous = keyMember.Value;
var changed = gui.Member(keyMember, @ignoreComposition: _perKeyAttributes == null);
if (changed)
keyMember.Value = previous;
}
else
{
gui.Member(keyMember, @ignoreComposition: _perKeyAttributes == null);
}
}
}
public void DrawValue(int index, int id)
{
var valueMember = GetElement(_valueElements, _kvpList.Values, index, id + 2);
using(gui.If(!_options.Readonly && typeof(TV).IsNumeric(), gui.LabelWidth(15f)))
{
if (_options.Readonly)
{
var previous = valueMember.Value;
var changed = gui.Member(valueMember, @ignoreComposition: _perValueAttributes == null);
if (changed)
valueMember.Value = previous;
}
else
{
gui.Member(valueMember, @ignoreComposition: _perValueAttributes == null);
}
}
}
private EditorMember GetElement<T>(List<EditorMember> elements, List<T> source, int index, int id)
{
if (index >= elements.Count)
{
Attribute[] attrs;
if (typeof(T) == typeof(TK))
attrs = _perKeyAttributes;
else
attrs = _perValueAttributes;
var element = EditorMember.WrapIListElement(
@elementName : typeof(T).IsNumeric() && !_options.Readonly ? "~" : string.Empty,
@elementType : typeof(T),
@elementId : RuntimeHelper.CombineHashCodes(id, index),
@attributes : attrs
);
element.InitializeIList(source, index, rawTarget, unityTarget);
elements.Add(element);
return element;
}
try
{
var e = elements[index];
e.Write = Write;
e.InitializeIList(source, index, rawTarget, unityTarget);
return e;
}
catch (ArgumentOutOfRangeException)
{
Log("DictionaryDrawer: Accessing element out of range. Index: {0} Count {1}. This shouldn't really happen. Please report it with information on how to replicate it".FormatWith(index, elements.Count));
return null;
}
}
private string FormatPair(TK key, TV value)
{
#if PROFILE
Profiler.BeginSample("DictionaryDrawer: FormatPair");
#endif
string format = formatPair(new KeyValuePair<TK, TV>(key, value));
#if PROFILE
Profiler.EndSample();
#endif
return format;
}
private Func<KeyValuePair<TK, TV>, string> _formatPair;
private Func<KeyValuePair<TK, TV>, string> formatPair
{
get
{
return _formatPair ?? (_formatPair = new Func<KeyValuePair<TK, TV>, string>(pair =>
{
var key = pair.Key;
var value = pair.Value;
var result = _formatPairPattern;
result = Regex.Replace(result, @"\$keytype", key == null ? "null" : key.GetType().GetNiceName());
result = Regex.Replace(result, @"\$valuetype", value == null ? "null" : value.GetType().GetNiceName());
result = Regex.Replace(result, @"\$key", GetObjectString(key));
result = Regex.Replace(result, @"\$value", GetObjectString(value));
//Debug.Log("New format: " + result);
return result;
}).Memoize());
}
}
private string GetObjectString(object from)
{
if (from.IsObjectNull())
return "null";
var obj = from as UnityObject;
if (obj != null)
return obj.name + " (" + obj.GetType().Name + ")";
var toStr = from.ToString();
return toStr == null ? "null" : toStr;
}
TK GetNewKey(IDictionary<TK, TV> from)
{
TK key;
if (typeof(TK) == typeof(string))
{
string prefix;
int postfix;
if (from.Count > 0)
{
prefix = from.Last().Key as string;
string postfixStr = "";
int i = prefix.Length - 1;
for (; i >= 0; i--)
{
char c = prefix[i];
if (!char.IsDigit(c))
break;
postfixStr = postfixStr.Insert(0, c.ToString());
}
if (int.TryParse(postfixStr, out postfix))
prefix = prefix.Remove(i + 1, postfixStr.Length);
}
else
{
prefix = "New Key ";
postfix = 0;
}
while(from.Keys.Contains((TK)(object)(prefix + postfix))) postfix++;
key = (TK)(object)(prefix + postfix);
}
else if (typeof(TK) == typeof(int))
{
var n = 0;
while (from.Keys.Contains((TK)(object)(n))) n++;
key = (TK)(object)n;
}
else if (typeof(TK).IsEnum)
{
var values = Enum.GetValues(typeof(TK)) as TK[];
var result = values.Except(from.Keys).ToList();
if (result.Count == 0)
return default(TK);
key = (TK)result[0];
}
else key = default(TK);
return key;
}
private void AddNewPair()
{
var key = _options.TempKey ? _tempKey : GetNewKey(_kvpList);
try
{
var value = default(TV);
if (_options.AddToLast)
_kvpList.Add(key, value);
else
_kvpList.Insert(0, key, value);
memberValue.Add(key, value);
var eKey = RuntimeHelper.CombineHashCodes(id, (_kvpList.Count - 1), "entry");
prefs[eKey] = true;
foldout = true;
if (_options.TempKey)
_tempKey = GetNewKey(_kvpList);
}
catch (ArgumentException)
{
Log("Key already exists: " + key);
}
}
private struct DictionaryOptions
{
public readonly bool Readonly;
public readonly bool ForceExpand;
public readonly bool HideHeader;
public readonly bool HorizontalPairs;
public readonly bool Filter;
public readonly bool AddToLast;
public readonly bool TempKey;
public readonly bool ManualAlloc;
public readonly bool HideButtons;
public DictionaryOptions(Dict options)
{
Readonly = options.HasFlag(Dict.Readonly);
ForceExpand = options.HasFlag(Dict.ForceExpand);
HideHeader = options.HasFlag(Dict.HideHeader);
HorizontalPairs = options.HasFlag(Dict.HorizontalPairs);
Filter = options.HasFlag(Dict.Filter);
AddToLast = options.HasFlag(Dict.AddToLast);
TempKey = options.HasFlag(Dict.TempKey);
ManualAlloc = options.HasFlag(Dict.ManualAlloc);
HideButtons = options.HasFlag(Dict.HideButtons);
}
}
}
}
| |
/*
* 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.IO;
using System.Net;
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 GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects region registration and neighbor lookups to the SimianGrid
/// backend
/// </summary>
public class SimianGridServiceConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
// private bool m_Enabled = false;
public SimianGridServiceConnector() { }
public SimianGridServiceConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public SimianGridServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
CommonInit(source);
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[SIMIAN GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceUrl = gridConfig.GetString("GridServerURI");
if (String.IsNullOrEmpty(serviceUrl))
{
m_log.Error("[SIMIAN GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_ServerURI = serviceUrl;
// m_Enabled = true;
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
Vector3d maxPosition = minPosition + new Vector3d(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight);
OSDMap extraData = new OSDMap
{
{ "ServerURI", OSD.FromString(regionInfo.ServerURI) },
{ "InternalAddress", OSD.FromString(regionInfo.InternalEndPoint.Address.ToString()) },
{ "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
{ "ExternalAddress", OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString()) },
{ "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
{ "MapTexture", OSD.FromUUID(regionInfo.TerrainImage) },
{ "Access", OSD.FromInteger(regionInfo.Access) },
{ "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
{ "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
{ "Token", OSD.FromString(regionInfo.Token) }
};
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionInfo.RegionID.ToString() },
{ "Name", regionInfo.RegionName },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Address", regionInfo.ServerURI },
{ "Enabled", "1" },
{ "ExtraData", OSDParser.SerializeJsonString(extraData) }
};
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
return String.Empty;
else
return "Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString();
}
public bool DeregisterRegion(UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionID.ToString() },
{ "Enabled", "0" }
};
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN GRID CONNECTOR]: Region deregistration for " + regionID + " failed: " + response["Message"].AsString());
return success;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
const int NEIGHBOR_RADIUS = 128;
GridRegion region = GetRegionByUUID(scopeID, regionID);
if (region != null)
{
List<GridRegion> regions = GetRegionRange(scopeID,
region.RegionLocX - NEIGHBOR_RADIUS, region.RegionLocX + (int)Constants.RegionSize + NEIGHBOR_RADIUS,
region.RegionLocY - NEIGHBOR_RADIUS, region.RegionLocY + (int)Constants.RegionSize + NEIGHBOR_RADIUS);
for (int i = 0; i < regions.Count; i++)
{
if (regions[i].RegionID == regionID)
{
regions.RemoveAt(i);
break;
}
}
// m_log.Debug("[SIMIAN GRID CONNECTOR]: Found " + regions.Count + " neighbors for region " + regionID);
return regions;
}
return new List<GridRegion>(0);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region with uuid {0}",regionID.ToString());
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] uuid request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID);
return null;
}
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
// Go one meter in from the requested x/y coords to avoid requesting a position
// that falls on the border of two sims
Vector3d position = new Vector3d(x + 1, y + 1, 0.0);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "Enabled", "1" }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request grid at {0}",position.ToString());
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] position request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
// m_log.InfoFormat("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at {0},{1}",
// x / Constants.RegionSize, y / Constants.RegionSize);
return null;
}
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
List<GridRegion> regions = GetRegionsByName(scopeID, regionName, 1);
m_log.Debug("[SIMIAN GRID CONNECTOR]: Got " + regions.Count + " matches for region name " + regionName);
if (regions.Count > 0)
return regions[0];
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "NameQuery", name },
{ "Enabled", "1" }
};
if (maxNumber > 0)
requestArgs["MaxNumber"] = maxNumber.ToString();
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions with name {0}",name);
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> foundRegions = new List<GridRegion>();
Vector3d minPosition = new Vector3d(xmin, ymin, 0.0);
Vector3d maxPosition = new Vector3d(xmax, ymax, Constants.RegionHeight);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Enabled", "1" }
};
//m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions by range {0} to {1}",minPosition.ToString(),maxPosition.ToString());
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
const int DEFAULT_X = 1000 * 256;
const int DEFAULT_Y = 1000 * 256;
GridRegion defRegion = GetNearestRegion(new Vector3d(DEFAULT_X, DEFAULT_Y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
GridRegion defRegion = GetNearestRegion(new Vector3d(x, y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "HyperGrid", "true" },
{ "Enabled", "1" }
};
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region flags for {0}",regionID.ToString());
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap extraData = response["ExtraData"] as OSDMap;
int enabled = response["Enabled"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.RegionOnline : 0;
int hypergrid = extraData["HyperGrid"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.Hyperlink : 0;
int flags = enabled | hypergrid;
m_log.DebugFormat("[SGGC] enabled - {0} hg - {1} flags - {2}", enabled, hypergrid, flags);
return flags;
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID + " during region flags check");
return -1;
}
}
#endregion IGridService
private GridRegion GetNearestRegion(Vector3d position, bool onlyEnabled)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "FindClosest", "1" }
};
if (onlyEnabled)
requestArgs["Enabled"] = "1";
OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at " + position);
return null;
}
}
private GridRegion ResponseToGridRegion(OSDMap response)
{
if (response == null)
return null;
OSDMap extraData = response["ExtraData"] as OSDMap;
if (extraData == null)
return null;
GridRegion region = new GridRegion();
region.RegionID = response["SceneID"].AsUUID();
region.RegionName = response["Name"].AsString();
Vector3d minPosition = response["MinPosition"].AsVector3d();
region.RegionLocX = (int)minPosition.X;
region.RegionLocY = (int)minPosition.Y;
if ( ! extraData["HyperGrid"] ) {
Uri httpAddress = response["Address"].AsUri();
region.ExternalHostName = httpAddress.Host;
region.HttpPort = (uint)httpAddress.Port;
IPAddress internalAddress;
IPAddress.TryParse(extraData["InternalAddress"].AsString(), out internalAddress);
if (internalAddress == null)
internalAddress = IPAddress.Any;
region.InternalEndPoint = new IPEndPoint(internalAddress, extraData["InternalPort"].AsInteger());
region.TerrainImage = extraData["MapTexture"].AsUUID();
region.Access = (byte)extraData["Access"].AsInteger();
region.RegionSecret = extraData["RegionSecret"].AsString();
region.EstateOwner = extraData["EstateOwner"].AsUUID();
region.Token = extraData["Token"].AsString();
region.ServerURI = extraData["ServerURI"].AsString();
} else {
region.ServerURI = response["Address"];
}
return region;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using CookComputing.XmlRpc;
namespace XenAPI
{
public partial class Session : XenObject<Session>
{
public const int STANDARD_TIMEOUT = 24 * 60 * 60 * 1000;
/// <summary>
/// This string is used as the HTTP UserAgent for each XML-RPC request.
/// </summary>
public static string UserAgent = string.Format("XenAPI/{0}", Helper.APIVersionString(API_Version.LATEST));
/// <summary>
/// If null, no proxy is used, otherwise this proxy is used for each XML-RPC request.
/// </summary>
public static IWebProxy Proxy = null;
public API_Version APIVersion = API_Version.API_1_1;
private Proxy _proxy;
private string _uuid;
public object Tag;
// Filled in after successful session_login_with_password for version 1.6 or newer connections
private bool _isLocalSuperuser = true;
private XenRef<Subject> _subject = null;
private string _userSid = null;
private string[] permissions = null;
private List<Role> roles = new List<Role>();
public Session(int timeout, string url)
{
_proxy = XmlRpcProxyGen.Create<Proxy>();
_proxy.Url = url;
_proxy.NonStandard = XmlRpcNonStandard.All;
_proxy.Timeout = timeout;
_proxy.UseIndentation = false;
_proxy.UserAgent = UserAgent;
_proxy.KeepAlive = true;
// Commenting these out as hooking these events cause problems in XmlRpcClientProtocol.cs#148
//_proxy.RequestEvent += LogRequest;
//_proxy.ResponseEvent += LogResponse;
_proxy.Proxy = Proxy;
}
public Session(string url)
: this(STANDARD_TIMEOUT, url)
{
}
public Session(int timeout, string host, int port)
: this(timeout, GetUrl(host, port))
{
}
public Session(string host, int port)
: this(STANDARD_TIMEOUT, host, port)
{
}
public Session(string url, string opaque_ref)
: this(STANDARD_TIMEOUT, url)
{
this._uuid = opaque_ref;
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
/// <summary>
/// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be
/// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host,
/// for example when you need to cancel an operation that is blocking the primary connection.
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
public Session(Session session, int timeout)
: this(timeout, session.Url)
{
_uuid = session.uuid;
APIVersion = session.APIVersion;
_isLocalSuperuser = session._isLocalSuperuser;
_subject = session._subject;
_userSid = session._userSid;
}
// Used after VDI.open_database
public static Session get_record(Session session, string _session)
{
Session newSession = new Session(STANDARD_TIMEOUT, session.proxy.Url);
newSession._uuid = _session;
newSession.SetAPIVersion();
return newSession;
}
private void SetADDetails()
{
_isLocalSuperuser = get_is_local_superuser();
if (IsLocalSuperuser)
return;
_subject = get_subject();
_userSid = get_auth_user_sid();
// Cache the details of this user to avoid making server calls later
// For example, some users get access to the pool through a group subject and will not be in the main cache
UserDetails.UpdateDetails(_userSid, this);
if (APIVersion <= API_Version.API_1_6) // Older versions have no RBAC, only AD
return;
// allRoles will contain every role on the server, permissions contains the subset of those that are available to this session.
permissions = Session.get_rbac_permissions(this, uuid);
Dictionary<XenRef<Role>,Role> allRoles = Role.get_all_records(this);
// every Role object is either a single api call (a permission) or has subroles and contains permissions through its descendants.
// We take out the parent Roles (VM-Admin etc.) into the Session.Roles field
foreach (string s in permissions)
{
foreach (XenRef<Role> xr in allRoles.Keys)
{
Role r = allRoles[xr];
if (r.subroles.Count > 0 && r.name_label == s)
{
r.opaque_ref = xr.opaque_ref;
roles.Add(r);
break;
}
}
}
}
/// <summary>
/// Retrieves the current users details from the UserDetails map. These values are only updated when a new session is created.
/// </summary>
public virtual UserDetails CurrentUserDetails
{
get
{
return _userSid == null ? null : UserDetails.Sid_To_UserDetails[_userSid];
}
}
public override void UpdateFrom(Session update)
{
throw new Exception("The method or operation is not implemented.");
}
public override string SaveChanges(Session session, string _serverOpaqueRef, Session serverObject)
{
throw new Exception("The method or operation is not implemented.");
}
public Proxy proxy
{
get { return _proxy; }
}
public string uuid
{
get { return _uuid; }
}
public string Url
{
get { return _proxy.Url; }
}
/// <summary>
/// Always true before API version 1.6.
/// </summary>
public virtual bool IsLocalSuperuser
{
get { return _isLocalSuperuser; }
}
/// <summary>
/// The OpaqueRef for the Subject under whose authority the current user is logged in;
/// may correspond to either a group or a user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public XenRef<Subject> Subject
{
get { return _subject; }
}
/// <summary>
/// The Active Directory SID of the currently logged-in user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public string UserSid
{
get { return _userSid; }
}
/// <summary>
/// All permissions associated with the session at the time of log in. This is the list xapi uses until the session is logged out;
/// even if the permitted roles change on the server side, they don't apply until the next session.
/// </summary>
public string[] Permissions
{
get { return permissions; }
}
/// <summary>
/// All roles associated with the session at the time of log in. Do not rely on roles for determining what a user can do,
/// instead use Permissions. This list should only be used for UI purposes.
/// </summary>
public List<Role> Roles
{
get { return roles; }
}
public void login_with_password(string username, string password)
{
_uuid = proxy.session_login_with_password(username, password).parse();
SetAPIVersion();
}
public void login_with_password(string username, string password, string version)
{
try
{
_uuid = proxy.session_login_with_password(username, password, version).parse();
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the 1.1 version instead.
login_with_password(username, password);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, string version, string originator)
{
try
{
_uuid = proxy.session_login_with_password(username, password, version, originator).parse();
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the pre-2.0 version instead.
login_with_password(username, password, version);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, API_Version version)
{
login_with_password(username, password, Helper.APIVersionString(version));
}
private void SetAPIVersion()
{
Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(this);
foreach (Pool pool in pools.Values)
{
Host host = Host.get_record(this, pool.master);
APIVersion = Helper.GetAPIVersion(host.API_version_major, host.API_version_minor);
break;
}
}
public void slave_local_login_with_password(string username, string password)
{
_uuid = proxy.session_slave_local_login_with_password(username, password).parse();
//assume the latest API
APIVersion = API_Version.LATEST;
}
public void logout()
{
logout(this);
}
/// <summary>
/// Log out of the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to log out</param>
public void logout(Session session2)
{
logout(session2._uuid);
session2._uuid = null;
}
/// <summary>
/// Log out of the session with the given reference, using this session for the connection.
/// </summary>
/// <param name="_self">The session to log out</param>
public void logout(string _self)
{
if (_self != null)
proxy.session_logout(_self).parse();
}
public void local_logout()
{
local_logout(this);
}
public void local_logout(Session session2)
{
local_logout(session2._uuid);
session2._uuid = null;
}
public void local_logout(string session_uuid)
{
if (session_uuid != null)
proxy.session_local_logout(session_uuid).parse();
}
public void change_password(string oldPassword, string newPassword)
{
change_password(this, oldPassword, newPassword);
}
/// <summary>
/// Change the password on the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to change</param>
public void change_password(Session session2, string oldPassword, string newPassword)
{
proxy.session_change_password(session2.uuid, oldPassword, newPassword).parse();
}
public string get_this_host()
{
return get_this_host(this, uuid);
}
public static string get_this_host(Session session, string _self)
{
return (string)session.proxy.session_get_this_host(session.uuid, _self ?? "").parse();
}
public string get_this_user()
{
return get_this_user(this, uuid);
}
public static string get_this_user(Session session, string _self)
{
return (string)session.proxy.session_get_this_user(session.uuid, _self ?? "").parse();
}
public bool get_is_local_superuser()
{
return get_is_local_superuser(this, uuid);
}
public static bool get_is_local_superuser(Session session, string _self)
{
return session.proxy.session_get_is_local_superuser(session.uuid, _self ?? "").parse();
}
public static string[] get_rbac_permissions(Session session, string _self)
{
return session.proxy.session_get_rbac_permissions(session.uuid, _self ?? "").parse();
}
public DateTime get_last_active()
{
return get_last_active(this, uuid);
}
public static DateTime get_last_active(Session session, string _self)
{
return session.proxy.session_get_last_active(session.uuid, _self ?? "").parse();
}
public bool get_pool()
{
return get_pool(this, uuid);
}
public static bool get_pool(Session session, string _self)
{
return (bool)session.proxy.session_get_pool(session.uuid, _self ?? "").parse();
}
public XenRef<Subject> get_subject()
{
return get_subject(this, uuid);
}
public static XenRef<Subject> get_subject(Session session, string _self)
{
return new XenRef<Subject>(session.proxy.session_get_subject(session.uuid, _self ?? "").parse());
}
public string get_auth_user_sid()
{
return get_auth_user_sid(this, uuid);
}
public static string get_auth_user_sid(Session session, string _self)
{
return (string)session.proxy.session_get_auth_user_sid(session.uuid, _self ?? "").parse();
}
#region AD SID enumeration and bootout
public string[] get_all_subject_identifiers()
{
return get_all_subject_identifiers(this);
}
public static string[] get_all_subject_identifiers(Session session)
{
return session.proxy.session_get_all_subject_identifiers(session.uuid).parse();
}
public XenRef<Task> async_get_all_subject_identifiers()
{
return async_get_all_subject_identifiers(this);
}
public static XenRef<Task> async_get_all_subject_identifiers(Session session)
{
return XenRef<Task>.Create(session.proxy.async_session_get_all_subject_identifiers(session.uuid).parse());
}
public string logout_subject_identifier(string subject_identifier)
{
return logout_subject_identifier(this, subject_identifier);
}
public static string logout_subject_identifier(Session session, string subject_identifier)
{
return session.proxy.session_logout_subject_identifier(session.uuid, subject_identifier).parse();
}
public XenRef<Task> async_logout_subject_identifier(string subject_identifier)
{
return async_logout_subject_identifier(this, subject_identifier);
}
public static XenRef<Task> async_logout_subject_identifier(Session session, string subject_identifier)
{
return XenRef<Task>.Create(session.proxy.async_session_logout_subject_identifier(session.uuid, subject_identifier).parse());
}
#endregion
#region other_config stuff
public Dictionary<string, string> get_other_config()
{
return get_other_config(this, uuid);
}
public static Dictionary<string, string> get_other_config(Session session, string _self)
{
return Maps.convert_from_proxy_string_string(session.proxy.session_get_other_config(session.uuid, _self ?? "").parse());
}
public void set_other_config(Dictionary<string, string> _other_config)
{
set_other_config(this, uuid, _other_config);
}
public static void set_other_config(Session session, string _self, Dictionary<string, string> _other_config)
{
session.proxy.session_set_other_config(session.uuid, _self ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
public void add_to_other_config(string _key, string _value)
{
add_to_other_config(this, uuid, _key, _value);
}
public static void add_to_other_config(Session session, string _self, string _key, string _value)
{
session.proxy.session_add_to_other_config(session.uuid, _self ?? "", _key ?? "", _value ?? "").parse();
}
public void remove_from_other_config(string _key)
{
remove_from_other_config(this, uuid, _key);
}
public static void remove_from_other_config(Session session, string _self, string _key)
{
session.proxy.session_remove_from_other_config(session.uuid, _self ?? "", _key ?? "").parse();
}
#endregion
static Session()
{
//ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
}
private static string GetUrl(string hostname, int port)
{
return string.Format("{0}://{1}:{2}", port==8080||port == 80 ? "http" : "https", hostname, port); // https, unless port=80
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}
| |
// Npgsql.NpgsqlCopySerializer.cs
//
// Author:
// Kalle Hallivuori <[email protected]>
//
// Copyright (C) 2007 The Npgsql Development Team
// [email protected]
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System;
using System.IO;
using System.Text;
namespace Revenj.DatabasePersistence.Postgres.Npgsql
{
/// <summary>
/// Writes given objects into a stream for PostgreSQL COPY in default copy format (not CSV or BINARY).
/// </summary>
public class NpgsqlCopySerializer
{
private static readonly Encoding ENCODING_UTF8 = Encoding.UTF8;
public static String DEFAULT_DELIMITER = "\t",
DEFAULT_SEPARATOR = "\n",
DEFAULT_NULL = "\\N",
DEFAULT_ESCAPE = "\\",
DEFAULT_QUOTE = "\"";
public static int DEFAULT_BUFFER_SIZE = 8192;
private readonly NpgsqlConnector _context;
private Stream _toStream;
private String _delimiter = DEFAULT_DELIMITER,
_escape = DEFAULT_ESCAPE,
_separator = DEFAULT_SEPARATOR,
_null = DEFAULT_NULL;
private byte[] _delimiterBytes = null, _escapeBytes = null, _separatorBytes = null, _nullBytes = null;
private byte[][] _escapeSequenceBytes = null;
private String[] _stringsToEscape = null;
private byte[] _sendBuffer = null;
private int _sendBufferAt = 0, _lastFieldEndAt = 0, _lastRowEndAt = 0, _atField = 0;
public NpgsqlCopySerializer(NpgsqlConnection conn)
{
_context = conn.Connector;
}
public bool IsActive
{
get { return _toStream != null && _context.Mediator.CopyStream == _toStream && _context.CurrentState is NpgsqlCopyInState; }
}
public Stream ToStream
{
get
{
if (_toStream == null)
{
_toStream = _context.Mediator.CopyStream;
}
return _toStream;
}
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change stream of an active " + this);
}
_toStream = value;
}
}
public String Delimiter
{
get { return _delimiter; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change delimiter of an active " + this);
}
_delimiter = value ?? DEFAULT_DELIMITER;
_delimiterBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] DelimiterBytes
{
get
{
if (_delimiterBytes == null)
{
_delimiterBytes = ENCODING_UTF8.GetBytes(_delimiter);
}
return _delimiterBytes;
}
}
public String Separator
{
get { return _separator; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change separator of an active " + this);
}
_separator = value ?? DEFAULT_SEPARATOR;
_separatorBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] SeparatorBytes
{
get
{
if (_separatorBytes == null)
{
_separatorBytes = ENCODING_UTF8.GetBytes(_separator);
}
return _separatorBytes;
}
}
public String Escape
{
get { return _escape; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change escape symbol of an active " + this);
}
_escape = value ?? DEFAULT_ESCAPE;
_escapeBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] EscapeBytes
{
get
{
if (_escapeBytes == null)
{
_escapeBytes = ENCODING_UTF8.GetBytes(_escape);
}
return _escapeBytes;
}
}
public String Null
{
get { return _null; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change null symbol of an active " + this);
}
_null = value ?? DEFAULT_NULL;
_nullBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] NullBytes
{
get
{
if (_nullBytes == null)
{
_nullBytes = ENCODING_UTF8.GetBytes(_null);
}
return _nullBytes;
}
}
public Int32 BufferSize
{
get { return _sendBuffer != null ? _sendBuffer.Length : DEFAULT_BUFFER_SIZE; }
set
{
byte[] _newBuffer = new byte[value];
if (_sendBuffer != null)
{
for (int i = 0; i < _sendBufferAt; i++)
{
_newBuffer[i] = _sendBuffer[i];
}
}
_sendBuffer = _newBuffer;
}
}
public void Flush()
{
if (_sendBufferAt > 0)
{
ToStream.Write(_sendBuffer, 0, _sendBufferAt);
ToStream.Flush();
}
_sendBufferAt = 0;
_lastRowEndAt = 0;
_lastFieldEndAt = 0;
}
public void FlushRows()
{
if (_lastRowEndAt > 0)
{
ToStream.Write(_sendBuffer, 0, _lastRowEndAt);
ToStream.Flush();
int len = _sendBufferAt - _lastRowEndAt;
for (int i = 0; i < len; i++)
{
_sendBuffer[i] = _sendBuffer[_lastRowEndAt + i];
}
_lastFieldEndAt -= _lastRowEndAt;
_sendBufferAt -= _lastRowEndAt;
_lastRowEndAt = 0;
}
}
public void FlushFields()
{
if (_lastFieldEndAt > 0)
{
ToStream.Write(_sendBuffer, 0, _lastFieldEndAt);
ToStream.Flush();
int len = _sendBufferAt - _lastFieldEndAt;
for (int i = 0; i < len; i++)
{
_sendBuffer[i] = _sendBuffer[_lastFieldEndAt + i];
}
_lastRowEndAt -= _lastFieldEndAt;
_sendBufferAt -= _lastFieldEndAt;
_lastFieldEndAt = 0;
}
}
public void Close()
{
if (_atField > 0)
{
EndRow();
}
Flush();
ToStream.Close();
}
protected int SpaceInBuffer
{
get { return BufferSize - _sendBufferAt; }
}
protected String[] StringsToEscape
{
get
{
if (_stringsToEscape == null)
{
_stringsToEscape = new String[] { Delimiter, Separator, Escape, "\r", "\n" };
}
return _stringsToEscape;
}
}
protected byte[][] EscapeSequenceBytes
{
get
{
if (_escapeSequenceBytes == null)
{
_escapeSequenceBytes = new byte[StringsToEscape.Length][];
for (int i = 0; i < StringsToEscape.Length; i++)
{
_escapeSequenceBytes[i] = EscapeSequenceFor(StringsToEscape[i].ToCharArray(0, 1)[0]);
}
}
return _escapeSequenceBytes;
}
}
private static readonly byte[] esc_t = new byte[] { (byte)'t' };
private static readonly byte[] esc_n = new byte[] { (byte)'n' };
private static readonly byte[] esc_r = new byte[] { (byte)'r' };
private static readonly byte[] esc_b = new byte[] { (byte)'b' };
private static readonly byte[] esc_f = new byte[] { (byte)'f' };
private static readonly byte[] esc_v = new byte[] { (byte)'v' };
protected static byte[] EscapeSequenceFor(char c)
{
return
c == '\t'
? esc_t
: c == '\n'
? esc_n
: c == '\r'
? esc_r
: c == '\b'
? esc_b
: c == '\f'
? esc_f
: c == '\v'
? esc_v
: (c < 32 || c > 127)
? new byte[] { (byte)('0' + ((c / 64) & 7)), (byte)('0' + ((c / 8) & 7)), (byte)('0' + (c & 7)) }
: new byte[] { (byte)c };
}
protected void MakeRoomForBytes(int len)
{
if (_sendBuffer == null)
{
_sendBuffer = new byte[BufferSize];
}
if (len >= SpaceInBuffer)
{
FlushRows();
if (len >= SpaceInBuffer)
{
FlushFields();
if (len >= SpaceInBuffer)
{
BufferSize = len;
}
}
}
}
protected void AddBytes(byte[] bytes)
{
MakeRoomForBytes(bytes.Length);
for (int i = 0; i < bytes.Length; i++)
{
_sendBuffer[_sendBufferAt++] = bytes[i];
}
}
public void EndRow()
{
if (_context != null)
{
while (_atField < _context.CurrentState.CopyFormat.FieldCount)
{
AddNull();
}
}
if (_context == null || !_context.CurrentState.CopyFormat.IsBinary)
{
AddBytes(SeparatorBytes);
}
_lastRowEndAt = _sendBufferAt;
_atField = 0;
}
protected void PrefixField()
{
if (_atField > 0)
{
if (_atField >= _context.CurrentState.CopyFormat.FieldCount)
{
throw new NpgsqlException("Tried to add too many fields to a copy record with " + _atField + " fields");
}
AddBytes(DelimiterBytes);
}
}
protected void FieldAdded()
{
_lastFieldEndAt = _sendBufferAt;
_atField++;
}
public void AddNull()
{
PrefixField();
AddBytes(NullBytes);
FieldAdded();
}
public void AddString(String fieldValue)
{
PrefixField();
int bufferedUpto = 0;
while (bufferedUpto < fieldValue.Length)
{
int escapeAt = fieldValue.Length;
byte[] escapeSequence = null;
// choose closest instance of strings to escape in fieldValue
for (int eachEscapeable = 0; eachEscapeable < StringsToEscape.Length; eachEscapeable++)
{
int i = fieldValue.IndexOf(StringsToEscape[eachEscapeable], bufferedUpto);
if (i > -1 && i < escapeAt)
{
escapeAt = i;
escapeSequence = EscapeSequenceBytes[eachEscapeable];
}
}
// some, possibly all of fieldValue string does not require escaping and can be buffered for output
if (escapeAt > bufferedUpto)
{
int encodedLength = ENCODING_UTF8.GetByteCount(fieldValue.ToCharArray(bufferedUpto, escapeAt - bufferedUpto));
MakeRoomForBytes(encodedLength);
_sendBufferAt += ENCODING_UTF8.GetBytes(fieldValue, bufferedUpto, escapeAt - bufferedUpto, _sendBuffer, _sendBufferAt);
bufferedUpto = escapeAt;
}
// now buffer the escape sequence for output
if (escapeSequence != null)
{
AddBytes(EscapeBytes);
AddBytes(escapeSequence);
bufferedUpto++;
}
}
FieldAdded();
}
public void AddInt32(Int32 fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddInt64(Int64 fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddNumber(double fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddBool(bool fieldValue)
{
AddString(fieldValue ? "TRUE" : "FALSE");
}
public void AddDateTime(DateTime fieldValue)
{
AddString(string.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}", fieldValue.Year, fieldValue.Month, fieldValue.Day, fieldValue.Hour, fieldValue.Minute, fieldValue.Second, fieldValue.Millisecond));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class DatabaseActivationOperationsExtensions
{
/// <summary>
/// Start an Azure SQL Data Warehouse database pause operation.To
/// determine the status of the operation call
/// GetDatabaseActivationOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// pause.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static DatabaseCreateOrUpdateResponse BeginPause(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseActivationOperations)s).BeginPauseAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start an Azure SQL Data Warehouse database pause operation.To
/// determine the status of the operation call
/// GetDatabaseActivationOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// pause.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static Task<DatabaseCreateOrUpdateResponse> BeginPauseAsync(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.BeginPauseAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Start an Azure SQL Data Warehouse database resume operation. To
/// determine the status of the operation call
/// GetDatabaseActivationOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// resume.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static DatabaseCreateOrUpdateResponse BeginResume(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseActivationOperations)s).BeginResumeAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start an Azure SQL Data Warehouse database resume operation. To
/// determine the status of the operation call
/// GetDatabaseActivationOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// resume.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static Task<DatabaseCreateOrUpdateResponse> BeginResumeAsync(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.BeginResumeAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure SQL Data Warehouse Database pause or
/// resume operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static DatabaseCreateOrUpdateResponse GetDatabaseActivationOperationStatus(this IDatabaseActivationOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseActivationOperations)s).GetDatabaseActivationOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure SQL Data Warehouse Database pause or
/// resume operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static Task<DatabaseCreateOrUpdateResponse> GetDatabaseActivationOperationStatusAsync(this IDatabaseActivationOperations operations, string operationStatusLink)
{
return operations.GetDatabaseActivationOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Start an Azure SQL Data Warehouse database pause operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// pause.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static DatabaseCreateOrUpdateResponse Pause(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseActivationOperations)s).PauseAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start an Azure SQL Data Warehouse database pause operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// pause.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static Task<DatabaseCreateOrUpdateResponse> PauseAsync(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.PauseAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Start an Azure SQL Data Warehouse database resume operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// resume.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static DatabaseCreateOrUpdateResponse Resume(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseActivationOperations)s).ResumeAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start an Azure SQL Data Warehouse database resume operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseActivationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the data
/// warehouse database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Data Warehouse database to
/// resume.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database operations.
/// </returns>
public static Task<DatabaseCreateOrUpdateResponse> ResumeAsync(this IDatabaseActivationOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ResumeAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpRequestMessageTest : HttpClientTestBase
{
Version _expectedRequestMessageVersion = !PlatformDetection.IsFullFramework ? new Version(2,0) : new Version(1, 1);
[Fact]
public void Ctor_Default_CorrectDefaults()
{
var rm = new HttpRequestMessage();
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(null, rm.RequestUri);
}
[Fact]
public void Ctor_RelativeStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "/relative");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(new Uri("/relative", UriKind.Relative), rm.RequestUri);
}
[Fact]
public void Ctor_AbsoluteStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "http://host/absolute/");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(new Uri("http://host/absolute/"), rm.RequestUri);
}
[Fact]
public void Ctor_NullStringUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (string)null);
Assert.Equal(null, rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
}
[Fact]
public void Ctor_RelativeUri_CorrectValues()
{
var uri = new Uri("/relative", UriKind.Relative);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_AbsoluteUri_CorrectValues()
{
var uri = new Uri("http://host/absolute/");
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_NullUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (Uri)null);
Assert.Equal(null, rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
}
[Fact]
public void Ctor_NullMethod_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new HttpRequestMessage(null, "http://example.com"));
}
[Fact]
public void Ctor_NonHttpUri_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("requestUri", () => new HttpRequestMessage(HttpMethod.Put, "ftp://example.com"));
}
[Fact]
public void Dispose_DisposeObject_ContentGetsDisposedAndSettersWillThrowButGettersStillWork()
{
var rm = new HttpRequestMessage(HttpMethod.Get, "http://example.com");
var content = new MockContent();
rm.Content = content;
Assert.False(content.IsDisposed);
rm.Dispose();
rm.Dispose(); // Multiple calls don't throw.
Assert.True(content.IsDisposed);
Assert.Throws<ObjectDisposedException>(() => { rm.Method = HttpMethod.Put; });
Assert.Throws<ObjectDisposedException>(() => { rm.RequestUri = null; });
Assert.Throws<ObjectDisposedException>(() => { rm.Version = new Version(1, 0); });
Assert.Throws<ObjectDisposedException>(() => { rm.Content = null; });
// Property getters should still work after disposing.
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(new Uri("http://example.com"), rm.RequestUri);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(content, rm.Content);
}
[Fact]
public void Properties_SetPropertiesAndGetTheirValue_MatchingValues()
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri("https://example.com");
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Properties);
}
[Fact]
public void RequestUri_SetNonHttpUri_ThrowsArgumentException()
{
var rm = new HttpRequestMessage();
AssertExtensions.Throws<ArgumentException>("value", () => { rm.RequestUri = new Uri("ftp://example.com"); });
}
[Fact]
public void Version_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Version = null; });
}
[Fact]
public void Method_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Method = null; });
}
[Fact]
public void ToString_DefaultAndNonDefaultInstance_DumpAllFields()
{
var rm = new HttpRequestMessage();
string expected =
"Method: GET, RequestUri: '<null>', Version: " +
_expectedRequestMessageVersion.ToString(2) +
", Content: <null>, Headers:\r\n{\r\n}";
Assert.Equal(expected, rm.ToString());
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri("http://a.com/");
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
// Note that there is no Content-Length header: The reason is that the value for Content-Length header
// doesn't get set by StringContent..ctor, but only if someone actually accesses the ContentLength property.
Assert.Equal(
"Method: PUT, RequestUri: 'http://a.com/', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
"}", rm.ToString());
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain", 0.2));
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml", 0.1));
rm.Headers.Add("Custom-Request-Header", "value1");
rm.Content.Headers.Add("Custom-Content-Header", "value2");
Assert.Equal(
"Method: PUT, RequestUri: 'http://a.com/', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Accept: text/plain; q=0.2\r\n" +
" Accept: text/xml; q=0.1\r\n" +
" Custom-Request-Header: value1\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
" Custom-Content-Header: value2\r\n" +
"}", rm.ToString());
}
[Theory]
[InlineData("DELETE")]
[InlineData("OPTIONS")]
[InlineData("HEAD")]
public async Task HttpRequest_BodylessMethod_NoContentLength(string method)
{
if (IsWinHttpHandler || IsNetfxHandler || IsUapHandler)
{
// Some platform handlers differ but we don't take it as failure.
return;
}
using (HttpClient client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
var request = new HttpRequestMessage();
request.RequestUri = uri;
request.Method = new HttpMethod(method);
Task<HttpResponseMessage> requestTask = client.SendAsync(request);
await server.AcceptConnectionAsync(async connection =>
{
List<string> headers = await connection.ReadRequestHeaderAsync();
Assert.DoesNotContain(headers, line => line.StartsWith("Content-length"));
await connection.SendResponseAsync();
await requestTask;
});
});
}
}
#region Helper methods
private class MockContent : HttpContent
{
public bool IsDisposed { get; private set; }
protected override bool TryComputeLength(out long length)
{
throw new NotImplementedException();
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
#endregion
}
}
| |
using J2N.Text;
using YAF.Lucene.Net.Diagnostics;
using YAF.Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using FlushInfo = YAF.Lucene.Net.Store.FlushInfo;
using IOContext = YAF.Lucene.Net.Store.IOContext;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using TermVectorsWriter = YAF.Lucene.Net.Codecs.TermVectorsWriter;
internal sealed class TermVectorsConsumer : TermsHashConsumer
{
internal TermVectorsWriter writer;
internal readonly DocumentsWriterPerThread docWriter;
internal readonly DocumentsWriterPerThread.DocState docState;
internal readonly BytesRef flushTerm = new BytesRef();
// Used by perField when serializing the term vectors
internal readonly ByteSliceReader vectorSliceReaderPos = new ByteSliceReader();
internal readonly ByteSliceReader vectorSliceReaderOff = new ByteSliceReader();
internal bool hasVectors;
internal int numVectorFields;
internal int lastDocID;
private TermVectorsConsumerPerField[] perFields = new TermVectorsConsumerPerField[1];
public TermVectorsConsumer(DocumentsWriterPerThread docWriter)
{
this.docWriter = docWriter;
docState = docWriter.docState;
}
// LUCENENE specific - original was internal, but FreqProxTermsWriter requires public (little point, since both are internal classes)
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Flush(IDictionary<string, TermsHashConsumerPerField> fieldsToFlush, SegmentWriteState state)
{
if (writer != null)
{
int numDocs = state.SegmentInfo.DocCount;
if (Debugging.AssertsEnabled) Debugging.Assert(numDocs > 0);
// At least one doc in this run had term vectors enabled
try
{
Fill(numDocs);
if (Debugging.AssertsEnabled) Debugging.Assert(state.SegmentInfo != null);
writer.Finish(state.FieldInfos, numDocs);
}
finally
{
IOUtils.Dispose(writer);
writer = null;
lastDocID = 0;
hasVectors = false;
}
}
foreach (TermsHashConsumerPerField field in fieldsToFlush.Values)
{
TermVectorsConsumerPerField perField = (TermVectorsConsumerPerField)field;
perField.termsHashPerField.Reset();
perField.ShrinkHash();
}
}
/// <summary>
/// Fills in no-term-vectors for all docs we haven't seen
/// since the last doc that had term vectors.
/// </summary>
internal void Fill(int docID)
{
while (lastDocID < docID)
{
writer.StartDocument(0);
writer.FinishDocument();
lastDocID++;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitTermVectorsWriter()
{
if (writer is null)
{
IOContext context = new IOContext(new FlushInfo(docWriter.NumDocsInRAM, docWriter.BytesUsed));
writer = docWriter.codec.TermVectorsFormat.VectorsWriter(docWriter.directory, docWriter.SegmentInfo, context);
lastDocID = 0;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal override void FinishDocument(TermsHash termsHash)
{
if (Debugging.AssertsEnabled) Debugging.Assert(docWriter.TestPoint("TermVectorsTermsWriter.finishDocument start"));
if (!hasVectors)
{
return;
}
InitTermVectorsWriter();
Fill(docState.docID);
// Append term vectors to the real outputs:
writer.StartDocument(numVectorFields);
for (int i = 0; i < numVectorFields; i++)
{
perFields[i].FinishDocument();
}
writer.FinishDocument();
if (Debugging.AssertsEnabled) Debugging.Assert(lastDocID == docState.docID,"lastDocID={0} docState.docID={1}", lastDocID, docState.docID);
lastDocID++;
termsHash.Reset();
Reset();
if (Debugging.AssertsEnabled) Debugging.Assert(docWriter.TestPoint("TermVectorsTermsWriter.finishDocument end"));
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
hasVectors = false;
if (writer != null)
{
writer.Abort();
writer = null;
}
lastDocID = 0;
Reset();
}
internal void Reset()
{
Arrays.Fill(perFields, null); // don't hang onto stuff from previous doc
numVectorFields = 0;
}
public override TermsHashConsumerPerField AddField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo)
{
return new TermVectorsConsumerPerField(termsHashPerField, this, fieldInfo);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void AddFieldToFlush(TermVectorsConsumerPerField fieldToFlush)
{
if (numVectorFields == perFields.Length)
{
int newSize = ArrayUtil.Oversize(numVectorFields + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
TermVectorsConsumerPerField[] newArray = new TermVectorsConsumerPerField[newSize];
Array.Copy(perFields, 0, newArray, 0, numVectorFields);
perFields = newArray;
}
perFields[numVectorFields++] = fieldToFlush;
}
internal override void StartDocument()
{
if (Debugging.AssertsEnabled) Debugging.Assert(ClearLastVectorFieldName());
Reset();
}
// Called only by assert
internal bool ClearLastVectorFieldName()
{
lastVectorFieldName = null;
return true;
}
// Called only by assert
internal string lastVectorFieldName;
internal bool VectorFieldsInOrder(FieldInfo fi)
{
try
{
return lastVectorFieldName != null ? lastVectorFieldName.CompareToOrdinal(fi.Name) < 0 : true;
}
finally
{
lastVectorFieldName = fi.Name;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using CanonicalizationDriver = System.IdentityModel.CanonicalizationDriver;
using Psha1DerivedKeyGenerator = System.IdentityModel.Psha1DerivedKeyGenerator;
abstract class SspiNegotiationTokenAuthenticator : NegotiationTokenAuthenticator<SspiNegotiationTokenAuthenticatorState>
{
ExtendedProtectionPolicy extendedProtectionPolicy;
string defaultServiceBinding;
Object thisLock = new Object();
protected SspiNegotiationTokenAuthenticator()
: base()
{
}
public ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get { return this.extendedProtectionPolicy; }
set { this.extendedProtectionPolicy = value; }
}
protected Object ThisLock
{
get { return this.thisLock; }
}
public string DefaultServiceBinding
{
get
{
if (this.defaultServiceBinding == null)
{
lock (ThisLock)
{
if (this.defaultServiceBinding == null)
{
this.defaultServiceBinding = SecurityUtils.GetSpnFromIdentity(
SecurityUtils.CreateWindowsIdentity(),
new EndpointAddress(ListenUri));
}
}
}
return this.defaultServiceBinding;
}
set { this.defaultServiceBinding = value; }
}
// abstract methods
public abstract XmlDictionaryString NegotiationValueType { get; }
protected abstract ReadOnlyCollection<IAuthorizationPolicy> ValidateSspiNegotiation(ISspiNegotiation sspiNegotiation);
protected abstract SspiNegotiationTokenAuthenticatorState CreateSspiState(byte[] incomingBlob, string incomingValueTypeUri);
// helpers
protected virtual void IssueServiceToken(SspiNegotiationTokenAuthenticatorState sspiState, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, out SecurityContextSecurityToken serviceToken, out WrappedKeySecurityToken proofToken,
out int issuedKeySize)
{
UniqueId contextId = SecurityUtils.GenerateUniqueId();
string id = SecurityUtils.GenerateId();
if (sspiState.RequestedKeySize == 0)
{
issuedKeySize = this.SecurityAlgorithmSuite.DefaultSymmetricKeyLength;
}
else
{
issuedKeySize = sspiState.RequestedKeySize;
}
byte[] key = new byte[issuedKeySize / 8];
CryptoHelper.FillRandomBytes(key);
DateTime effectiveTime = DateTime.UtcNow;
DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
serviceToken = IssueSecurityContextToken(contextId, id, key, effectiveTime, expirationTime, authorizationPolicies, this.EncryptStateInServiceToken);
proofToken = new WrappedKeySecurityToken(string.Empty, key, sspiState.SspiNegotiation);
}
protected virtual void ValidateIncomingBinaryNegotiation(BinaryNegotiation incomingNego)
{
if (incomingNego == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoBinaryNegoToReceive)));
}
incomingNego.Validate(this.NegotiationValueType);
}
protected virtual BinaryNegotiation GetOutgoingBinaryNegotiation(ISspiNegotiation sspiNegotiation, byte[] outgoingBlob)
{
return new BinaryNegotiation(this.NegotiationValueType, outgoingBlob);
}
static void AddToDigest(HashAlgorithm negotiationDigest, Stream stream)
{
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
CanonicalizationDriver canonicalizer = new CanonicalizationDriver();
canonicalizer.SetInput(stream);
byte[] canonicalizedData = canonicalizer.GetBytes();
lock (negotiationDigest)
{
negotiationDigest.TransformBlock(canonicalizedData, 0, canonicalizedData.Length, canonicalizedData, 0);
}
}
static void AddToDigest(SspiNegotiationTokenAuthenticatorState sspiState, RequestSecurityToken rst)
{
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
rst.RequestSecurityTokenXml.WriteTo(writer);
writer.Flush();
AddToDigest(sspiState.NegotiationDigest, stream);
}
static void AddToDigest(SspiNegotiationTokenAuthenticatorState sspiState, RequestSecurityTokenResponse rstr, bool wasReceived)
{
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
if (wasReceived)
{
rstr.RequestSecurityTokenResponseXml.WriteTo(writer);
}
else
{
rstr.WriteTo(writer);
}
writer.Flush();
AddToDigest(sspiState.NegotiationDigest, stream);
}
static byte[] ComputeAuthenticator(SspiNegotiationTokenAuthenticatorState sspiState, byte[] key)
{
byte[] negotiationHash;
lock (sspiState.NegotiationDigest)
{
sspiState.NegotiationDigest.TransformFinalBlock(CryptoHelper.EmptyBuffer, 0, 0);
negotiationHash = sspiState.NegotiationDigest.Hash;
}
Psha1DerivedKeyGenerator generator = new Psha1DerivedKeyGenerator(key);
return generator.GenerateDerivedKey(SecurityUtils.CombinedHashLabel, negotiationHash, SecurityNegotiationConstants.NegotiationAuthenticatorSize, 0);
}
// overrides
protected override bool IsMultiLegNegotiation
{
get
{
return true;
}
}
protected override Binding GetNegotiationBinding(Binding binding)
{
return binding;
}
protected override MessageFilter GetListenerFilter()
{
return new SspiNegotiationFilter(this);
}
protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out SspiNegotiationTokenAuthenticatorState negotiationState)
{
if (request == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
}
if (requestSecurityToken == null)
{
throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
}
if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
{
throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
}
BinaryNegotiation incomingNego = requestSecurityToken.GetBinaryNegotiation();
ValidateIncomingBinaryNegotiation(incomingNego);
negotiationState = CreateSspiState(incomingNego.GetNegotiationData(), incomingNego.ValueTypeUri);
AddToDigest(negotiationState, requestSecurityToken);
negotiationState.Context = requestSecurityToken.Context;
if (requestSecurityToken.KeySize != 0)
{
WSTrust.Driver.ValidateRequestedKeySize(requestSecurityToken.KeySize, this.SecurityAlgorithmSuite);
}
negotiationState.RequestedKeySize = requestSecurityToken.KeySize;
string appliesToName;
string appliesToNamespace;
requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
{
DataContractSerializer serializer;
if (request.Version.Addressing == AddressingVersion.WSAddressing10)
{
serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
negotiationState.AppliesTo = requestSecurityToken.GetAppliesTo<EndpointAddress10>(serializer).ToEndpointAddress();
}
else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
{
serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
negotiationState.AppliesTo = requestSecurityToken.GetAppliesTo<EndpointAddressAugust2004>(serializer).ToEndpointAddress();
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
}
negotiationState.AppliesToSerializer = serializer;
}
return ProcessNegotiation(negotiationState, request, incomingNego);
}
protected override BodyWriter ProcessRequestSecurityTokenResponse(SspiNegotiationTokenAuthenticatorState negotiationState, Message request, RequestSecurityTokenResponse requestSecurityTokenResponse)
{
if (request == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
}
if (requestSecurityTokenResponse == null)
{
throw TraceUtility.ThrowHelperArgumentNull("requestSecurityTokenResponse", request);
}
if (requestSecurityTokenResponse.Context != negotiationState.Context)
{
throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.BadSecurityNegotiationContext)), request);
}
AddToDigest(negotiationState, requestSecurityTokenResponse, true);
BinaryNegotiation incomingNego = requestSecurityTokenResponse.GetBinaryNegotiation();
ValidateIncomingBinaryNegotiation(incomingNego);
return ProcessNegotiation(negotiationState, request, incomingNego);
}
BodyWriter ProcessNegotiation(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
{
ISspiNegotiation sspiNegotiation = negotiationState.SspiNegotiation;
byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(),
SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
this.extendedProtectionPolicy);
if (sspiNegotiation.IsValidContext == false)
{
throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidSspiNegotiation)), incomingMessage);
}
// if there is no blob to send back the nego must be complete from the server side
if (outgoingBlob == null && sspiNegotiation.IsCompleted == false)
{
throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoBinaryNegoToSend)), incomingMessage);
}
BinaryNegotiation outgoingBinaryNegotiation;
if (outgoingBlob != null)
{
outgoingBinaryNegotiation = GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
}
else
{
outgoingBinaryNegotiation = null;
}
BodyWriter replyBody;
if (sspiNegotiation.IsCompleted)
{
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = ValidateSspiNegotiation(sspiNegotiation);
SecurityContextSecurityToken serviceToken;
WrappedKeySecurityToken proofToken;
int issuedKeySize;
IssueServiceToken(negotiationState, authorizationPolicies, out serviceToken, out proofToken, out issuedKeySize);
negotiationState.SetServiceToken(serviceToken);
SecurityKeyIdentifierClause externalTokenReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
SecurityKeyIdentifierClause internalTokenReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
RequestSecurityTokenResponse dummyRstr = new RequestSecurityTokenResponse(this.StandardsManager);
dummyRstr.Context = negotiationState.Context;
dummyRstr.KeySize = issuedKeySize;
dummyRstr.TokenType = this.SecurityContextTokenUri;
if (outgoingBinaryNegotiation != null)
{
dummyRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
}
dummyRstr.RequestedUnattachedReference = externalTokenReference;
dummyRstr.RequestedAttachedReference = internalTokenReference;
dummyRstr.SetLifetime(serviceToken.ValidFrom, serviceToken.ValidTo);
if (negotiationState.AppliesTo != null)
{
if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
{
dummyRstr.SetAppliesTo<EndpointAddress10>(EndpointAddress10.FromEndpointAddress(
negotiationState.AppliesTo),
negotiationState.AppliesToSerializer);
}
else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
{
dummyRstr.SetAppliesTo<EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(
negotiationState.AppliesTo),
negotiationState.AppliesToSerializer);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
}
}
dummyRstr.MakeReadOnly();
AddToDigest(negotiationState, dummyRstr, false);
RequestSecurityTokenResponse negotiationRstr = new RequestSecurityTokenResponse(this.StandardsManager);
negotiationRstr.RequestedSecurityToken = serviceToken;
negotiationRstr.RequestedProofToken = proofToken;
negotiationRstr.Context = negotiationState.Context;
negotiationRstr.KeySize = issuedKeySize;
negotiationRstr.TokenType = this.SecurityContextTokenUri;
if (outgoingBinaryNegotiation != null)
{
negotiationRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
}
negotiationRstr.RequestedAttachedReference = internalTokenReference;
negotiationRstr.RequestedUnattachedReference = externalTokenReference;
if (negotiationState.AppliesTo != null)
{
if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
{
negotiationRstr.SetAppliesTo<EndpointAddress10>(
EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo),
negotiationState.AppliesToSerializer);
}
else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
{
negotiationRstr.SetAppliesTo<EndpointAddressAugust2004>(
EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo),
negotiationState.AppliesToSerializer);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
}
}
negotiationRstr.MakeReadOnly();
byte[] authenticator = ComputeAuthenticator(negotiationState, serviceToken.GetKeyBytes());
RequestSecurityTokenResponse authenticatorRstr = new RequestSecurityTokenResponse(this.StandardsManager);
authenticatorRstr.Context = negotiationState.Context;
authenticatorRstr.SetAuthenticator(authenticator);
authenticatorRstr.MakeReadOnly();
List<RequestSecurityTokenResponse> rstrList = new List<RequestSecurityTokenResponse>(2);
rstrList.Add(negotiationRstr);
rstrList.Add(authenticatorRstr);
replyBody = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
}
else
{
RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
rstr.Context = negotiationState.Context;
rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
rstr.MakeReadOnly();
AddToDigest(negotiationState, rstr, false);
replyBody = rstr;
}
return replyBody;
}
class SspiNegotiationFilter : HeaderFilter
{
SspiNegotiationTokenAuthenticator authenticator;
public SspiNegotiationFilter(SspiNegotiationTokenAuthenticator authenticator)
{
this.authenticator = authenticator;
}
public override bool Match(Message message)
{
if (message.Headers.Action == authenticator.RequestSecurityTokenAction.Value
|| message.Headers.Action == authenticator.RequestSecurityTokenResponseAction.Value)
{
return !SecurityVersion.Default.DoesMessageContainSecurityHeader(message);
}
else
{
return false;
}
}
}
}
}
| |
/*
* 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 DotNetOpenMail;
using DotNetOpenMail.SmtpAuth;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
namespace OpenSim.Region.CoreModules.Scripting.EmailModules
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EmailModule")]
public class EmailModule : ISharedRegionModule, IEmailModule
{
//
// Log
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private IConfigSource m_Config;
private bool m_Enabled = false;
private string m_HostName = string.Empty;
private string m_InterObjectHostname = "lsl.opensim.local";
private Dictionary<UUID, DateTime> m_LastGetEmailCall = new Dictionary<UUID, DateTime>();
private Dictionary<UUID, List<Email>> m_MailQueues = new Dictionary<UUID, List<Email>>();
private int m_MaxEmailSize = 4096;
private int m_MaxQueueSize = 50;
// maximum size of an object mail queue
private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0);
// Scenes by Region Handle
private Dictionary<ulong, Scene> m_Scenes =
new Dictionary<ulong, Scene>();
//private string m_RegionName = string.Empty;
private string SMTP_SERVER_HOSTNAME = string.Empty;
private string SMTP_SERVER_LOGIN = string.Empty;
private string SMTP_SERVER_PASSWORD = string.Empty;
private int SMTP_SERVER_PORT = 25;
// 2 hours without llGetNextEmail drops the queue
// largest email allowed by default, as per lsl docs.
#region ISharedRegionModule
public string Name
{
get { return "DefaultEmailModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// It's a go!
lock (m_Scenes)
{
// Claim the interface slot
scene.RegisterModuleInterface<IEmailModule>(this);
// Add to scene list
if (m_Scenes.ContainsKey(scene.RegionInfo.RegionHandle))
{
m_Scenes[scene.RegionInfo.RegionHandle] = scene;
}
else
{
m_Scenes.Add(scene.RegionInfo.RegionHandle, scene);
}
}
m_log.Info("[EMAIL] Activated DefaultEmailModule");
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
m_Config = config;
IConfig SMTPConfig;
//FIXME: RegionName is correct??
//m_RegionName = scene.RegionInfo.RegionName;
IConfig startupConfig = m_Config.Configs["Startup"];
m_Enabled = (startupConfig.GetString("emailmodule", "DefaultEmailModule") == "DefaultEmailModule");
//Load SMTP SERVER config
try
{
if ((SMTPConfig = m_Config.Configs["SMTP"]) == null)
{
m_Enabled = false;
return;
}
if (!SMTPConfig.GetBoolean("enabled", false))
{
m_Enabled = false;
return;
}
m_HostName = SMTPConfig.GetString("host_domain_header_from", m_HostName);
m_InterObjectHostname = SMTPConfig.GetString("internal_object_host", m_InterObjectHostname);
SMTP_SERVER_HOSTNAME = SMTPConfig.GetString("SMTP_SERVER_HOSTNAME", SMTP_SERVER_HOSTNAME);
SMTP_SERVER_PORT = SMTPConfig.GetInt("SMTP_SERVER_PORT", SMTP_SERVER_PORT);
SMTP_SERVER_LOGIN = SMTPConfig.GetString("SMTP_SERVER_LOGIN", SMTP_SERVER_LOGIN);
SMTP_SERVER_PASSWORD = SMTPConfig.GetString("SMTP_SERVER_PASSWORD", SMTP_SERVER_PASSWORD);
m_MaxEmailSize = SMTPConfig.GetInt("email_max_size", m_MaxEmailSize);
}
catch (Exception e)
{
m_log.Error("[EMAIL] DefaultEmailModule not configured: " + e.Message);
m_Enabled = false;
return;
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
#endregion ISharedRegionModule
/// <summary>
///
/// </summary>
/// <param name="objectID"></param>
/// <param name="sender"></param>
/// <param name="subject"></param>
/// <returns></returns>
public Email GetNextEmail(UUID objectID, string sender, string subject)
{
List<Email> queue = null;
lock (m_LastGetEmailCall)
{
if (m_LastGetEmailCall.ContainsKey(objectID))
{
m_LastGetEmailCall.Remove(objectID);
}
m_LastGetEmailCall.Add(objectID, DateTime.Now);
// Hopefully this isn't too time consuming. If it is, we can always push it into a worker thread.
DateTime now = DateTime.Now;
List<UUID> removal = new List<UUID>();
foreach (UUID uuid in m_LastGetEmailCall.Keys)
{
if ((now - m_LastGetEmailCall[uuid]) > m_QueueTimeout)
{
removal.Add(uuid);
}
}
foreach (UUID remove in removal)
{
m_LastGetEmailCall.Remove(remove);
lock (m_MailQueues)
{
m_MailQueues.Remove(remove);
}
}
}
lock (m_MailQueues)
{
if (m_MailQueues.ContainsKey(objectID))
{
queue = m_MailQueues[objectID];
}
}
if (queue != null)
{
lock (queue)
{
if (queue.Count > 0)
{
int i;
for (i = 0; i < queue.Count; i++)
{
if ((sender == null || sender.Equals("") || sender.Equals(queue[i].sender)) &&
(subject == null || subject.Equals("") || subject.Equals(queue[i].subject)))
{
break;
}
}
if (i != queue.Count)
{
Email ret = queue[i];
queue.Remove(ret);
ret.numLeft = queue.Count;
return ret;
}
}
}
}
else
{
lock (m_MailQueues)
{
m_MailQueues.Add(objectID, new List<Email>());
}
}
return null;
}
public void InsertEmail(UUID to, Email email)
{
// It's tempting to create the queue here. Don't; objects which have
// not yet called GetNextEmail should have no queue, and emails to them
// should be silently dropped.
lock (m_MailQueues)
{
if (m_MailQueues.ContainsKey(to))
{
if (m_MailQueues[to].Count >= m_MaxQueueSize)
{
// fail silently
return;
}
lock (m_MailQueues[to])
{
m_MailQueues[to].Add(email);
}
}
}
}
/// <summary>
/// SendMail function utilized by llEMail
/// </summary>
/// <param name="objectID"></param>
/// <param name="address"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
public void SendEmail(UUID objectID, string address, string subject, string body)
{
//Check if address is empty
if (address == string.Empty)
return;
//FIXED:Check the email is correct form in REGEX
string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
+ @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ @"[a-zA-Z]{2,}))$";
Regex EMailreStrict = new Regex(EMailpatternStrict);
bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
if (!isEMailStrictMatch)
{
m_log.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
return;
}
if ((subject.Length + body.Length) > m_MaxEmailSize)
{
m_log.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
return;
}
string LastObjectName = string.Empty;
string LastObjectPosition = string.Empty;
string LastObjectRegionName = string.Empty;
resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
if (!address.EndsWith(m_InterObjectHostname))
{
// regular email, send it out
try
{
//Creation EmailMessage
EmailMessage emailMessage = new EmailMessage();
//From
emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
//To - Only One
emailMessage.AddToAddress(new EmailAddress(address));
//Subject
emailMessage.Subject = subject;
//TEXT Body
resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
emailMessage.BodyText = "Object-Name: " + LastObjectName +
"\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
LastObjectPosition + "\n\n" + body;
//Config SMTP Server
//Set SMTP SERVER config
SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
// Add authentication only when requested
//
if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
{
//Authentication
smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
}
//Send Email Message
emailMessage.Send(smtpServer);
//Log
m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
}
catch (Exception e)
{
m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
}
}
else
{
// inter object email, keep it in the family
Email email = new Email();
email.time = ((int)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).ToString();
email.subject = subject;
email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
email.message = "Object-Name: " + LastObjectName +
"\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
LastObjectPosition + "\n\n" + body;
string guid = address.Substring(0, address.IndexOf("@"));
UUID toID = new UUID(guid);
if (IsLocal(toID)) // TODO FIX check to see if it is local
{
// object in this region
InsertEmail(toID, email);
}
else
{
// object on another region
// TODO FIX
}
}
}
private SceneObjectPart findPrim(UUID objectID, out string ObjectRegionName)
{
lock (m_Scenes)
{
foreach (Scene s in m_Scenes.Values)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
if (part != null)
{
ObjectRegionName = s.RegionInfo.RegionName;
uint localX = s.RegionInfo.WorldLocX;
uint localY = s.RegionInfo.WorldLocY;
ObjectRegionName = ObjectRegionName + " (" + localX + ", " + localY + ")";
return part;
}
}
}
ObjectRegionName = string.Empty;
return null;
}
private bool IsLocal(UUID objectID)
{
string unused;
return (null != findPrim(objectID, out unused));
}
private void resolveNamePositionRegionName(UUID objectID, out string ObjectName, out string ObjectAbsolutePosition, out string ObjectRegionName)
{
string m_ObjectRegionName;
int objectLocX;
int objectLocY;
int objectLocZ;
SceneObjectPart part = findPrim(objectID, out m_ObjectRegionName);
if (part != null)
{
objectLocX = (int)part.AbsolutePosition.X;
objectLocY = (int)part.AbsolutePosition.Y;
objectLocZ = (int)part.AbsolutePosition.Z;
ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
ObjectName = part.Name;
ObjectRegionName = m_ObjectRegionName;
return;
}
objectLocX = (int)part.AbsolutePosition.X;
objectLocY = (int)part.AbsolutePosition.Y;
objectLocZ = (int)part.AbsolutePosition.Z;
ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
ObjectName = part.Name;
ObjectRegionName = m_ObjectRegionName;
return;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Collections.Generic;
using System.Windows.Forms;
namespace TestCentric.Gui.Presenters
{
using Model;
using Views;
/// <summary>
/// TreeViewPresenter is the presenter for the TestTreeView
/// </summary>
public class TreeViewPresenter
{
private ITestTreeView _view;
private ITestModel _model;
private DisplayStrategy _strategy;
private ITestItem _selectedTestItem;
private Dictionary<string, TreeNode> _nodeIndex = new Dictionary<string, TreeNode>();
#region Constructor
public TreeViewPresenter(ITestTreeView treeView, ITestModel model)
{
_view = treeView;
_model = model;
Settings = new Settings.TestTreeSettings(_model.Services.UserSettings);
InitializeRunCommands();
WireUpEvents();
}
#endregion
#region Private Members
private void WireUpEvents()
{
// Model actions
_model.Events.TestLoaded += (ea) =>
{
_strategy.OnTestLoaded(ea.Test);
InitializeRunCommands();
};
_model.Events.TestReloaded += (ea) =>
{
_strategy.OnTestLoaded(ea.Test);
InitializeRunCommands();
};
_model.Events.TestUnloaded += (ea) =>
{
_strategy.OnTestUnloaded();
InitializeRunCommands();
};
_model.Events.RunStarting += (ea) => InitializeRunCommands();
_model.Events.RunFinished += (ea) => InitializeRunCommands();
_model.Events.TestFinished += (ea) => _strategy.OnTestFinished(ea.Result);
_model.Events.SuiteFinished += (ea) => _strategy.OnTestFinished(ea.Result);
// View actions - Initial Load
_view.Load += (s, e) =>
{
SetDefaultDisplayStrategy();
};
// View context commands
_view.Tree.ContextMenu.Popup += () =>
_view.RunCheckedCommand.Visible = _view.Tree.CheckBoxes && _view.Tree.CheckedNodes.Count > 0;
_view.CollapseAllCommand.Execute += () => _view.CollapseAll();
_view.ExpandAllCommand.Execute += () => _view.ExpandAll();
_view.CollapseToFixturesCommand.Execute += () => _strategy.CollapseToFixtures();
_view.ShowCheckBoxes.CheckedChanged += () => _view.Tree.CheckBoxes = _view.ShowCheckBoxes.Checked; ;
_view.RunContextCommand.Execute += () =>
{
if (_selectedTestItem != null)
_model.RunTests(_selectedTestItem);
};
_view.RunCheckedCommand.Execute += RunCheckedTests;
// Node selected in tree
_view.Tree.SelectedNodeChanged += (tn) =>
{
_selectedTestItem = tn.Tag as ITestItem;
_model.NotifySelectedItemChanged(_selectedTestItem);
};
// Run button and dropdowns
_view.RunButton.Execute += () =>
{
// Necessary test because we don't disable the button click
if (_model.HasTests && !_model.IsTestRunning)
_model.RunAllTests();
};
_view.RunAllCommand.Execute += () => _model.RunAllTests();
_view.RunSelectedCommand.Execute += () => _model.RunTests(_selectedTestItem);
_view.RunFailedCommand.Execute += () => _model.RunAllTests(); // NYI
_view.StopRunCommand.Execute += () => _model.CancelTestRun();
// Change of display format
_view.DisplayFormat.SelectionChanged += () =>
{
SetDisplayStrategy(_view.DisplayFormat.SelectedItem);
_strategy.Reload();
};
}
private void RunCheckedTests()
{
var tests = new TestGroup("RunTests");
foreach (var treeNode in _view.Tree.CheckedNodes)
{
var testNode = treeNode.Tag as TestNode;
if (testNode != null)
tests.Add(testNode);
else
{
var group = treeNode.Tag as TestGroup;
if (group != null)
tests.AddRange(group);
}
}
_model.RunTests(tests);
}
private void InitializeRunCommands()
{
bool isRunning = _model.IsTestRunning;
bool canRun = _model.HasTests && !isRunning;
// TODO: Figure out how to disable the button click but not the dropdown.
//_view.RunButton.Enabled = canRun;
_view.RunAllCommand.Enabled = canRun;
_view.RunSelectedCommand.Enabled = canRun;
_view.RunFailedCommand.Enabled = canRun;
_view.StopRunCommand.Enabled = isRunning;
}
private void SetDefaultDisplayStrategy()
{
CreateDisplayStrategy(Settings.DisplayFormat);
}
private void SetDisplayStrategy(string format)
{
CreateDisplayStrategy(format);
Settings.DisplayFormat = format;
}
private void CreateDisplayStrategy(string format)
{
switch (format.ToUpperInvariant())
{
default:
case "NUNIT_TREE":
_strategy = new NUnitTreeDisplayStrategy(_view, _model);
break;
case "FIXTURE_LIST":
_strategy = new FixtureListDisplayStrategy(_view, _model);
break;
case "TEST_LIST":
_strategy = new TestListDisplayStrategy(_view, _model);
break;
}
_view.FormatButton.ToolTipText = _strategy.Description;
_view.DisplayFormat.SelectedItem = format;
}
private Settings.TestTreeSettings Settings { get; }
#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.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// AcceptSocket property variables.
internal Socket _acceptSocket;
private Socket _connectSocket;
// Buffer,Offset,Count property variables.
internal byte[] _buffer;
internal int _count;
internal int _offset;
// BufferList property variables.
internal IList<ArraySegment<byte>> _bufferList;
// BytesTransferred property variables.
private int _bytesTransferred;
// Completed event property variables.
private event EventHandler<SocketAsyncEventArgs> _completed;
private bool _completedChanged;
// LastOperation property variables.
private SocketAsyncOperation _completedOperation;
// ReceiveMessageFromPacketInfo property variables.
private IPPacketInformation _receiveMessageFromPacketInfo;
// RemoteEndPoint property variables.
private EndPoint _remoteEndPoint;
// SendPacketsSendSize property variable.
internal int _sendPacketsSendSize;
// SendPacketsElements property variables.
internal SendPacketsElement[] _sendPacketsElements;
// SocketError property variables.
private SocketError _socketError;
private Exception _connectByNameError;
// SocketFlags property variables.
internal SocketFlags _socketFlags;
// UserToken property variables.
private object _userToken;
// Internal buffer for AcceptEx when Buffer not supplied.
internal byte[] _acceptBuffer;
internal int _acceptAddressBufferCount;
// Internal SocketAddress buffer.
internal Internals.SocketAddress _socketAddress;
// Misc state variables.
private ExecutionContext _context;
private static readonly ContextCallback s_executionCallback = ExecutionCallback;
private Socket _currentSocket;
private bool _disposeCalled;
// Controls thread safety via Interlocked.
private const int Configuring = -1;
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private MultipleConnectAsync _multipleConnect;
private static bool s_loggingEnabled = SocketsEventSource.Log.IsEnabled();
public SocketAsyncEventArgs()
{
InitializeInternals();
}
public Socket AcceptSocket
{
get { return _acceptSocket; }
set { _acceptSocket = value; }
}
public Socket ConnectSocket
{
get { return _connectSocket; }
}
public byte[] Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
// NOTE: this property is mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will throw.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
StartConfiguring();
try
{
if (value != null && _buffer != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "Buffer"));
}
_bufferList = value;
SetupMultipleBuffers();
}
finally
{
Complete();
}
}
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public event EventHandler<SocketAsyncEventArgs> Completed
{
add
{
_completed += value;
_completedChanged = true;
}
remove
{
_completed -= value;
_completedChanged = true;
}
}
protected virtual void OnCompleted(SocketAsyncEventArgs e)
{
EventHandler<SocketAsyncEventArgs> handler = _completed;
if (handler != null)
{
handler(e._currentSocket, e);
}
}
public SocketAsyncOperation LastOperation
{
get { return _completedOperation; }
}
public IPPacketInformation ReceiveMessageFromPacketInfo
{
get { return _receiveMessageFromPacketInfo; }
}
public EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
public SendPacketsElement[] SendPacketsElements
{
get { return _sendPacketsElements; }
set
{
StartConfiguring();
try
{
_sendPacketsElements = value;
SetupSendPacketsElements();
}
finally
{
Complete();
}
}
}
public int SendPacketsSendSize
{
get { return _sendPacketsSendSize; }
set { _sendPacketsSendSize = value; }
}
public SocketError SocketError
{
get { return _socketError; }
set { _socketError = value; }
}
public Exception ConnectByNameError
{
get { return _connectByNameError; }
}
public SocketFlags SocketFlags
{
get { return _socketFlags; }
set { _socketFlags = value; }
}
public object UserToken
{
get { return _userToken; }
set { _userToken = value; }
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
SetBufferInternal(buffer, offset, count);
}
public void SetBuffer(int offset, int count)
{
SetBufferInternal(_buffer, offset, count);
}
private void SetBufferInternal(byte[] buffer, int offset, int count)
{
StartConfiguring();
try
{
if (buffer == null)
{
// Clear out existing buffer.
_buffer = null;
_offset = 0;
_count = 0;
}
else
{
// Can't have both Buffer and BufferList.
if (_bufferList != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "BufferList"));
}
// Offset and count can't be negative and the
// combination must be in bounds of the array.
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
_buffer = buffer;
_offset = offset;
_count = count;
}
// Pin new or unpin old buffer if necessary.
SetupSingleBuffer();
}
finally
{
Complete();
}
}
internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
_socketError = socketError;
_connectByNameError = null;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
}
internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
{
_connectByNameError = exception;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
if (exception == null)
{
_socketError = SocketError.Success;
}
else
{
SocketException socketException = exception as SocketException;
if (socketException != null)
{
_socketError = socketException.SocketErrorCode;
}
else
{
_socketError = SocketError.SocketError;
}
}
}
private static void ExecutionCallback(object state)
{
var thisRef = (SocketAsyncEventArgs)state;
thisRef.OnCompleted(thisRef);
}
// Marks this object as no longer "in-use". Will also execute a Dispose deferred
// because I/O was in progress.
internal void Complete()
{
// Mark as not in-use.
_operating = Free;
InnerComplete();
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Dispose call to implement IDisposable.
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// OK to dispose now.
FreeInternals(false);
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
~SocketAsyncEventArgs()
{
FreeInternals(true);
}
// NOTE: Use a try/finally to make sure Complete is called when you're done
private void StartConfiguring()
{
int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
if (status == InProgress || status == Configuring)
{
throw new InvalidOperationException(SR.net_socketopinprogress);
}
else if (status == Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
// Prepares for a native async socket call.
// This method performs the tasks common to all socket operations.
internal void StartOperationCommon(Socket socket)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
// Only one at a time.
throw new InvalidOperationException(SR.net_socketopinprogress);
}
// Prepare execution context for callback.
// If event delegates have changed or socket has changed
// then discard any existing context.
if (_completedChanged || socket != _currentSocket)
{
_completedChanged = false;
_context = null;
}
// Capture execution context if none already.
if (_context == null)
{
_context = ExecutionContext.Capture();
}
// Remember current socket.
_currentSocket = socket;
}
internal void StartOperationAccept()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Accept;
// AcceptEx needs a single buffer with room for two special sockaddr data structures.
// It can also take additional buffer space in front of those special sockaddr
// structures that can be filled in with initial data coming in on a connection.
// First calculate the special AcceptEx address buffer size.
// It is the size of two native sockaddr buffers with 16 extra bytes each.
// The native sockaddr buffers vary by address family so must reference the current socket.
_acceptAddressBufferCount = 2 * (_currentSocket._rightEndPoint.Serialize().Size + 16);
// If our caller specified a buffer (willing to get received data with the Accept) then
// it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
// Throw if that buffer is not large enough.
bool userSuppliedBuffer = _buffer != null;
if (userSuppliedBuffer)
{
// Caller specified a buffer - see if it is large enough
if (_count < _acceptAddressBufferCount)
{
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, "Count"));
}
// Buffer is already pinned if necessary.
}
else
{
// Caller didn't specify a buffer so use an internal one.
// See if current internal one is big enough, otherwise create a new one.
if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
{
_acceptBuffer = new byte[_acceptAddressBufferCount];
}
}
InnerStartOperationAccept(userSuppliedBuffer);
}
internal void StartOperationConnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = null;
_connectSocket = null;
InnerStartOperationConnect();
}
internal void StartOperationWrapperConnect(MultipleConnectAsync args)
{
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = args;
_connectSocket = null;
}
internal void CancelConnectAsync()
{
if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect)
{
if (_multipleConnect != null)
{
// If a multiple connect is in progress, abort it.
_multipleConnect.Cancel();
}
else
{
// Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket.
// _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
if (_currentSocket == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
}
Debug.Fail("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
}
_currentSocket.Dispose();
}
}
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Receive;
InnerStartOperationReceive();
}
internal void StartOperationReceiveFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveFrom;
InnerStartOperationReceiveFrom();
}
internal void StartOperationReceiveMessageFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveMessageFrom;
InnerStartOperationReceiveMessageFrom();
}
internal void StartOperationSend()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Send;
InnerStartOperationSend();
}
internal void StartOperationSendPackets()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendPackets;
InnerStartOperationSendPackets();
}
internal void StartOperationSendTo()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendTo;
InnerStartOperationSendTo();
}
internal void UpdatePerfCounters(int size, bool sendOp)
{
if (sendOp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent);
}
}
else
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived);
}
}
}
internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
}
internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
}
internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
_currentSocket = connectSocket;
_connectSocket = connectSocket;
// Complete the operation and raise the event.
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
switch (_completedOperation)
{
case SocketAsyncOperation.Accept:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Get the endpoint.
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
socketError = FinishOperationAccept(remoteSocketAddress);
if (socketError == SocketError.Success)
{
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
if (s_loggingEnabled)
SocketsEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
}
else
{
SetResults(socketError, bytesTransferred, SocketFlags.None);
_acceptSocket = null;
}
break;
case SocketAsyncOperation.Connect:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
socketError = FinishOperationConnect();
// Mark socket connected.
if (socketError == SocketError.Success)
{
if (s_loggingEnabled)
SocketsEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
}
break;
case SocketAsyncOperation.Disconnect:
_currentSocket.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.Receive:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
break;
case SocketAsyncOperation.ReceiveFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
break;
case SocketAsyncOperation.ReceiveMessageFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
FinishOperationReceiveMessageFrom();
break;
case SocketAsyncOperation.Send:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
case SocketAsyncOperation.SendPackets:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogSendPacketsBuffers(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
FinishOperationSendPackets();
break;
case SocketAsyncOperation.SendTo:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
}
if (socketError != SocketError.Success)
{
// Asynchronous failure or something went wrong after async success.
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
// Complete the operation and raise completion event.
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
}
}
| |
namespace android.content
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.content.AsyncQueryHandler_))]
public abstract partial class AsyncQueryHandler : android.os.Handler
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AsyncQueryHandler()
{
InitJNI();
}
protected AsyncQueryHandler(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
protected sealed partial class WorkerArgs : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static WorkerArgs()
{
InitJNI();
}
internal WorkerArgs(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.FieldId _uri1062;
public global::android.net.Uri uri
{
get
{
return default(global::android.net.Uri);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _handler1063;
public global::android.os.Handler handler
{
get
{
return default(global::android.os.Handler);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _projection1064;
public global::java.lang.String[] projection
{
get
{
return default(global::java.lang.String[]);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _selection1065;
public global::java.lang.String selection
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _selectionArgs1066;
public global::java.lang.String[] selectionArgs
{
get
{
return default(global::java.lang.String[]);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _orderBy1067;
public global::java.lang.String orderBy
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _result1068;
public global::java.lang.Object result
{
get
{
return default(global::java.lang.Object);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _cookie1069;
public global::java.lang.Object cookie
{
get
{
return default(global::java.lang.Object);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _values1070;
public global::android.content.ContentValues values
{
get
{
return default(global::android.content.ContentValues);
}
set
{
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.AsyncQueryHandler.WorkerArgs.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler$WorkerArgs"));
}
}
[global::MonoJavaBridge.JavaClass()]
protected partial class WorkerHandler : android.os.Handler
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static WorkerHandler()
{
InitJNI();
}
protected WorkerHandler(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _handleMessage1071;
public override void handleMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.WorkerHandler._handleMessage1071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.WorkerHandler.staticClass, global::android.content.AsyncQueryHandler.WorkerHandler._handleMessage1071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _WorkerHandler1072;
public WorkerHandler(android.content.AsyncQueryHandler arg0, android.os.Looper arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.AsyncQueryHandler.WorkerHandler.staticClass, global::android.content.AsyncQueryHandler.WorkerHandler._WorkerHandler1072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.AsyncQueryHandler.WorkerHandler.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler$WorkerHandler"));
global::android.content.AsyncQueryHandler.WorkerHandler._handleMessage1071 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.WorkerHandler.staticClass, "handleMessage", "(Landroid/os/Message;)V");
global::android.content.AsyncQueryHandler.WorkerHandler._WorkerHandler1072 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.WorkerHandler.staticClass, "<init>", "(Landroid/content/AsyncQueryHandler;Landroid/os/Looper;)V");
}
}
internal static global::MonoJavaBridge.MethodId _handleMessage1073;
public override void handleMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._handleMessage1073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._handleMessage1073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _createHandler1074;
protected virtual global::android.os.Handler createHandler(android.os.Looper arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._createHandler1074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Handler;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._createHandler1074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Handler;
}
internal static global::MonoJavaBridge.MethodId _startQuery1075;
public virtual void startQuery(int arg0, java.lang.Object arg1, android.net.Uri arg2, java.lang.String[] arg3, java.lang.String arg4, java.lang.String[] arg5, java.lang.String arg6)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._startQuery1075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._startQuery1075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6));
}
internal static global::MonoJavaBridge.MethodId _cancelOperation1076;
public virtual void cancelOperation(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._cancelOperation1076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._cancelOperation1076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _startInsert1077;
public virtual void startInsert(int arg0, java.lang.Object arg1, android.net.Uri arg2, android.content.ContentValues arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._startInsert1077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._startInsert1077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _startUpdate1078;
public virtual void startUpdate(int arg0, java.lang.Object arg1, android.net.Uri arg2, android.content.ContentValues arg3, java.lang.String arg4, java.lang.String[] arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._startUpdate1078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._startUpdate1078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
internal static global::MonoJavaBridge.MethodId _startDelete1079;
public virtual void startDelete(int arg0, java.lang.Object arg1, android.net.Uri arg2, java.lang.String arg3, java.lang.String[] arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._startDelete1079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._startDelete1079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _onQueryComplete1080;
protected virtual void onQueryComplete(int arg0, java.lang.Object arg1, android.database.Cursor arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._onQueryComplete1080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._onQueryComplete1080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onInsertComplete1081;
protected virtual void onInsertComplete(int arg0, java.lang.Object arg1, android.net.Uri arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._onInsertComplete1081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._onInsertComplete1081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onUpdateComplete1082;
protected virtual void onUpdateComplete(int arg0, java.lang.Object arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._onUpdateComplete1082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._onUpdateComplete1082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onDeleteComplete1083;
protected virtual void onDeleteComplete(int arg0, java.lang.Object arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler._onDeleteComplete1083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._onDeleteComplete1083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _AsyncQueryHandler1084;
public AsyncQueryHandler(android.content.ContentResolver arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._AsyncQueryHandler1084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.AsyncQueryHandler.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler"));
global::android.content.AsyncQueryHandler._handleMessage1073 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "handleMessage", "(Landroid/os/Message;)V");
global::android.content.AsyncQueryHandler._createHandler1074 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "createHandler", "(Landroid/os/Looper;)Landroid/os/Handler;");
global::android.content.AsyncQueryHandler._startQuery1075 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "startQuery", "(ILjava/lang/Object;Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V");
global::android.content.AsyncQueryHandler._cancelOperation1076 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "cancelOperation", "(I)V");
global::android.content.AsyncQueryHandler._startInsert1077 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "startInsert", "(ILjava/lang/Object;Landroid/net/Uri;Landroid/content/ContentValues;)V");
global::android.content.AsyncQueryHandler._startUpdate1078 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "startUpdate", "(ILjava/lang/Object;Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)V");
global::android.content.AsyncQueryHandler._startDelete1079 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "startDelete", "(ILjava/lang/Object;Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)V");
global::android.content.AsyncQueryHandler._onQueryComplete1080 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "onQueryComplete", "(ILjava/lang/Object;Landroid/database/Cursor;)V");
global::android.content.AsyncQueryHandler._onInsertComplete1081 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "onInsertComplete", "(ILjava/lang/Object;Landroid/net/Uri;)V");
global::android.content.AsyncQueryHandler._onUpdateComplete1082 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "onUpdateComplete", "(ILjava/lang/Object;I)V");
global::android.content.AsyncQueryHandler._onDeleteComplete1083 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "onDeleteComplete", "(ILjava/lang/Object;I)V");
global::android.content.AsyncQueryHandler._AsyncQueryHandler1084 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "<init>", "(Landroid/content/ContentResolver;)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.content.AsyncQueryHandler))]
public sealed partial class AsyncQueryHandler_ : android.content.AsyncQueryHandler
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AsyncQueryHandler_()
{
InitJNI();
}
internal AsyncQueryHandler_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.AsyncQueryHandler_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler"));
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Mail.Net
{
#region usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
#endregion
/// <summary>
/// This class provides usefull text methods.
/// </summary>
public class TextUtils
{
#region Methods
/// <summary>
/// Qoutes and escapes fishy(\") chars.
/// </summary>
/// <param name="text">Text to quote.</param>
/// <returns></returns>
public static string QuoteString(string text)
{
StringBuilder retVal = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '\\')
{
retVal.Append("\\\\");
}
else if (c == '\"')
{
retVal.Append("\\\"");
}
else
{
retVal.Append(c);
}
}
return "\"" + retVal + "\"";
}
/// <summary>
/// Unquotes and unescapes escaped chars specified text. For example "xxx" will become to 'xxx', "escaped quote \"", will become to escaped 'quote "'.
/// </summary>
/// <param name="text">Text to unquote.</param>
/// <returns></returns>
public static string UnQuoteString(string text)
{
int startPosInText = 0;
int endPosInText = text.Length;
//--- Trim. We can't use standard string.Trim(), it's slow. ----//
for (int i = 0; i < endPosInText; i++)
{
char c = text[i];
if (c == ' ' || c == '\t')
{
startPosInText++;
}
else
{
break;
}
}
for (int i = endPosInText - 1; i > 0; i--)
{
char c = text[i];
if (c == ' ' || c == '\t')
{
endPosInText--;
}
else
{
break;
}
}
//--------------------------------------------------------------//
// All text trimmed
if ((endPosInText - startPosInText) <= 0)
{
return "";
}
// Remove starting and ending quotes.
if (text[startPosInText] == '\"')
{
startPosInText++;
}
if (text[endPosInText - 1] == '\"')
{
endPosInText--;
}
// Just '"'
if (endPosInText == startPosInText - 1)
{
return "";
}
char[] chars = new char[endPosInText - startPosInText];
int posInChars = 0;
bool charIsEscaped = false;
for (int i = startPosInText; i < endPosInText; i++)
{
char c = text[i];
// Escaping char
if (!charIsEscaped && c == '\\')
{
charIsEscaped = true;
}
// Escaped char
else if (charIsEscaped)
{
// TODO: replace \n,\r,\t,\v ???
chars[posInChars] = c;
posInChars++;
charIsEscaped = false;
}
// Normal char
else
{
chars[posInChars] = c;
posInChars++;
charIsEscaped = false;
}
}
return new string(chars, 0, posInChars);
}
/// <summary>
/// Escapes specified chars in the specified string.
/// </summary>
/// <param name="text">Text to escape.</param>
/// <param name="charsToEscape">Chars to escape.</param>
public static string EscapeString(string text, char[] charsToEscape)
{
// Create worst scenario buffer, assume all chars must be escaped
char[] buffer = new char[text.Length*2];
int nChars = 0;
foreach (char c in text)
{
foreach (char escapeChar in charsToEscape)
{
if (c == escapeChar)
{
buffer[nChars] = '\\';
nChars++;
break;
}
}
buffer[nChars] = c;
nChars++;
}
return new string(buffer, 0, nChars);
}
/// <summary>
/// Unescapes all escaped chars.
/// </summary>
/// <param name="text">Text to unescape.</param>
/// <returns></returns>
public static string UnEscapeString(string text)
{
// Create worst scenarion buffer, non of the chars escaped.
char[] buffer = new char[text.Length];
int nChars = 0;
bool escapedCahr = false;
foreach (char c in text)
{
if (!escapedCahr && c == '\\')
{
escapedCahr = true;
}
else
{
buffer[nChars] = c;
nChars++;
escapedCahr = false;
}
}
return new string(buffer, 0, nChars);
}
/// <summary>
/// Splits string into string arrays. This split method won't split qouted strings, but only text outside of qouted string.
/// For example: '"text1, text2",text3' will be 2 parts: "text1, text2" and text3.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char that splits text.</param>
/// <returns></returns>
public static string[] SplitQuotedString(string text, char splitChar)
{
return SplitQuotedString(text, splitChar, false);
}
/// <summary>
/// Splits string into string arrays. This split method won't split qouted strings, but only text outside of qouted string.
/// For example: '"text1, text2",text3' will be 2 parts: "text1, text2" and text3.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char that splits text.</param>
/// <param name="unquote">If true, splitted parst will be unqouted if they are qouted.</param>
/// <returns></returns>
public static string[] SplitQuotedString(string text, char splitChar, bool unquote)
{
List<string> splitParts = new List<string>(); // Holds splitted parts
int startPos = 0;
bool inQuotedString = false; // Holds flag if position is quoted string or not
char lastChar = '0';
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
// Start/end quoted string area. Ingonre escaped \".
if (lastChar != '\\' && c == '\"')
{
inQuotedString = !inQuotedString;
}
// Current char is split char and it isn't in quoted string, do split
if (!inQuotedString && c == splitChar)
{
// Add current currentSplitBuffer value to splitted parts list
if (unquote)
{
splitParts.Add(UnQuoteString(text.Substring(startPos, i - startPos)));
}
else
{
splitParts.Add(text.Substring(startPos, i - startPos));
}
// Store new split part start position.
startPos = i + 1;
}
lastChar = c;
}
// Add last split part to splitted parts list
if (unquote)
{
splitParts.Add(UnQuoteString(text.Substring(startPos, text.Length - startPos)));
}
else
{
splitParts.Add(text.Substring(startPos, text.Length - startPos));
}
return splitParts.ToArray();
}
/// <summary>
/// Gets first index of specified char. The specified char in quoted string is skipped.
/// Returns -1 if specified char doesn't exist.
/// </summary>
/// <param name="text">Text in what to check.</param>
/// <param name="indexChar">Char what index to get.</param>
/// <returns></returns>
public static int QuotedIndexOf(string text, char indexChar)
{
int retVal = -1;
bool inQuotedString = false; // Holds flag if position is quoted string or not
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '\"')
{
// Start/end quoted string area
inQuotedString = !inQuotedString;
}
// Current char is what index we want and it isn't in quoted string, return it's index
if (!inQuotedString && c == indexChar)
{
return i;
}
}
return retVal;
}
/// <summary>
/// Splits string into string arrays.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char Char that splits text.</param>
/// <returns></returns>
public static string[] SplitString(string text, char splitChar)
{
ArrayList splitParts = new ArrayList(); // Holds splitted parts
int lastSplitPoint = 0;
int textLength = text.Length;
for (int i = 0; i < textLength; i++)
{
if (text[i] == splitChar)
{
// Add current currentSplitBuffer value to splitted parts list
splitParts.Add(text.Substring(lastSplitPoint, i - lastSplitPoint));
lastSplitPoint = i + 1;
}
}
// Add last split part to splitted parts list
if (lastSplitPoint <= textLength)
{
splitParts.Add(text.Substring(lastSplitPoint));
}
string[] retVal = new string[splitParts.Count];
splitParts.CopyTo(retVal, 0);
return retVal;
}
/// <summary>
/// Gets if specified string is valid "token" value.
/// </summary>
/// <param name="value">String value to check.</param>
/// <returns>Returns true if specified string value is valid "token" value.</returns>
/// <exception cref="ArgumentNullException">Is raised if <b>value</b> is null.</exception>
public static bool IsToken(string value)
{
if (value == null)
{
throw new ArgumentNullException(value);
}
/* This syntax is taken from rfc 3261, but token must be universal so ... .
token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
alphanum = ALPHA / DIGIT
ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
DIGIT = %x30-39 ; 0-9
*/
char[] tokenChars = new[] {'-', '.', '!', '%', '*', '_', '+', '`', '\'', '~'};
foreach (char c in value)
{
// We don't have letter or digit, so we only may have token char.
if (!((c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) || (c >= 0x30 && c <= 0x39)))
{
bool validTokenChar = false;
foreach (char tokenChar in tokenChars)
{
if (c == tokenChar)
{
validTokenChar = true;
break;
}
}
if (!validTokenChar)
{
return false;
}
}
}
return true;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MusicHouse.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.Threading;
using MindTouch.Tasking;
using NUnit.Framework;
namespace MindTouch.Dream.Test {
public class ResultTestException : Exception {
public ResultTestException() { }
public ResultTestException(string message) : base(message) { }
}
[TestFixture]
public class ResultTest {
#region --- Valid Transitions ---
[Test]
public void Return_Wait() {
Test<int>(
false,
result => {
result.Return(1);
},
result => {
/* do nothing */
}, true, null, false, null,
null
);
}
[Test]
public void Wait_Return() {
Test<int>(
true,
result => {
result.Return(1);
},
result => {
/* do nothing */
}, true, null, false, null,
null
);
}
[Test]
public void Throw_Wait() {
Test<int>(
false,
result => {
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Wait_Throw() {
Test<int>(
true,
result => {
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Wait_Timeout() {
Test<int>(
false,
result => {
/* do nothing */
},
result => {
/* do nothing */
},
false, typeof(TimeoutException), false, null,
null
);
}
[Test]
public void Wait_Timeout_Return() {
Test<int>(
false,
result => {
/* do nothing */
},
result => {
result.Return(1);
},
false, typeof(TimeoutException), true, 1,
null
);
}
[Test]
public void Wait_Timeout_Throw() {
Test<int>(
false,
result => {
/* do nothing */
}, result => {
result.Throw(new ResultTestException());
},
false, typeof(TimeoutException), true, typeof(ResultTestException),
null
);
}
[Test]
public void Wait_Timeout_Cancel() {
Test<int>(
false,
result => {
/* do nothing */
},
result => {
result.Cancel();
},
false, typeof(TimeoutException), false, null,
null
);
}
[Test]
public void Wait_Timeout_ConfirmCancel() {
Test<int>(
false,
result => {
/* do nothing */
}, result => {
result.ConfirmCancel();
},
false, typeof(TimeoutException), true, null,
null
);
}
[Test]
public void Wait_Timeout_Cancel_Return() {
Test<int>(
false,
result => {
/* do nothing */
},
result => {
result.Cancel();
result.Return(1);
},
false, typeof(TimeoutException), true, 1,
null
);
}
[Test]
public void Wait_Timeout_Cancel_Throw() {
Test<int>(
false,
result => {
/* do nothing */
}, result => {
result.Cancel();
result.Throw(new ResultTestException());
},
false, typeof(TimeoutException), true, typeof(ResultTestException),
null
);
}
[Test]
public void Wait_Timeout_Cancel_ConfirmCancel() {
Test<int>(
false,
result => {
/* do nothing */
}, result => {
result.Cancel();
result.ConfirmCancel();
},
false, typeof(TimeoutException), true, null,
null
);
}
[Test]
public void Cancel_Return_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.Return(1);
},
result => {
/* do nothing */
},
true, null, false, null,
null
);
}
[Test]
public void Cancel_Cancel_Return_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.Cancel();
result.Return(1);
},
result => {
/* do nothing */
},
true, null, false, null,
null
);
}
[Test]
public void Cancel_HasFinished_Return_Wait() {
Test<int>(
false,
result => {
result.Cancel();
bool finished = result.HasFinished;
result.Return(1);
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, 1,
null
);
}
[Test]
public void Cancel_HasFinished_Confirm_Wait() {
Test<int>(
false,
result => {
result.Cancel();
bool finished = result.HasFinished;
result.ConfirmCancel();
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, null,
null
);
}
[Test]
public void Wait_Cancel_Return() {
Test<int>(
true,
result => {
result.Cancel();
result.Return(1);
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, 1,
null
);
}
[Test]
public void Wait_Cancel_Cancel_Return() {
Test<int>(
true,
result => {
result.Cancel();
result.Cancel();
result.Return(1);
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, 1,
null
);
}
[Test]
public void Cancel_Throw_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Cancel_Cancel_Throw_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.Cancel();
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Cancel_HasFinished_Throw_Wait() {
Test<int>(
false,
result => {
result.Cancel();
bool finished = result.HasFinished;
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, typeof(ResultTestException),
null
);
}
[Test]
public void Wait_Cancel_Throw() {
Test<int>(
true,
result => {
result.Cancel();
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, typeof(ResultTestException),
null
);
}
[Test]
public void Wait_Cancel_Cancel_Throw() {
Test<int>(
true,
result => {
result.Cancel();
result.Cancel();
result.Throw(new ResultTestException());
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, typeof(ResultTestException),
null
);
}
[Test]
public void Return_Cancel_Wait() {
Test<int>(
false,
result => {
result.Return(1);
result.Cancel();
},
result => {
/* do nothing */
},
true, null, false, null,
null
);
}
[Test]
public void Wait_Return_Cancel() {
Test<int>(
true,
result => {
result.Return(1);
result.Cancel();
},
result => {
/* do nothing */
},
true, null, false, null,
null
);
}
[Test]
public void Throw_Cancel_Wait() {
Test<int>(
false,
result => {
result.Throw(new ResultTestException());
result.Cancel();
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Wait_Throw_Cancel() {
Test<int>(
true,
result => {
result.Throw(new ResultTestException());
result.Cancel();
},
result => {
/* do nothing */
},
false, typeof(ResultTestException), false, null,
null
);
}
[Test]
public void Cancel_ConfirmCancel_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.ConfirmCancel();
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, null,
null
);
}
[Test]
public void Cancel_ConfirmCancel_Cancel_Wait() {
Test<int>(
false,
result => {
result.Cancel();
result.ConfirmCancel();
result.Cancel();
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, null,
null
);
}
[Test]
public void Wait_Cancel_ConfirmCancel() {
Test<int>(
true,
result => {
result.Cancel();
result.ConfirmCancel();
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, null,
null
);
}
[Test]
public void Wait_Cancel_ConfirmCancel_Cancel() {
Test<int>(
true,
result => {
result.Cancel();
result.ConfirmCancel();
result.Cancel();
},
result => {
/* do nothing */
},
false, typeof(CanceledException), true, null,
null
);
}
#endregion
#region --- TryReturn ---
[Test]
public void TryReturn() {
var result = new Result<int>();
var test = result.TryReturn(2);
Assert.IsTrue(test, "TryReturn failed");
Assert.IsTrue(result.HasValue, "result value is missing");
Assert.AreEqual(2, result.Value, "result value does not match");
}
[Test]
public void Return_TryReturn() {
var result = new Result<int>();
result.Return(1);
var test = result.TryReturn(2);
Assert.IsFalse(test, "TryReturn succeeded");
Assert.IsTrue(result.HasValue, "result value is missing");
Assert.AreEqual(1, result.Value, "result value does not match");
}
[Test]
public void Throw_TryReturn() {
var result = new Result<int>();
result.Throw(new ResultTestException());
var test = result.TryReturn(2);
Assert.IsFalse(test, "TryReturn succeeded");
Assert.IsTrue(result.HasException, "result exception is missing");
Assert.IsInstanceOfType(typeof(ResultTestException), result.Exception, "result exception has wrong type");
}
[Ignore("Not fully baked yet")]
[Test]
public void Cancel_TryReturn() {
var result = new Result<int>();
result.Cancel();
var test = result.TryReturn(2);
Assert.IsFalse(test, "TryReturn succeeded");
Assert.IsTrue(result.IsCanceled, "result is not canceled");
Assert.IsTrue(result.HasException, "result exception is missing");
Assert.IsInstanceOfType(typeof(CanceledException), result.Exception, "result exception has wrong type");
}
#endregion
#region --- Invalid Transitions ---
[Test]
public void Return_Return() {
TestFail<int>(
result => {
result.Return(1);
result.Return(2);
},
typeof(InvalidOperationException), null,
result => result.HasValue && (result.Value == 1)
);
}
[Test]
public void Return_Throw() {
TestFail<int>(
result => {
result.Return(1);
result.Throw(new ResultTestException());
},
typeof(InvalidOperationException), null,
result => result.HasValue && (result.Value == 1)
);
}
[Test]
public void Throw_Return() {
TestFail<int>(
result => {
result.Throw(new ResultTestException());
result.Return(1);
},
typeof(InvalidOperationException), null,
result => result.HasException && (result.Exception is ResultTestException)
);
}
[Test]
public void Throw_Throw() {
TestFail<int>(
result => {
result.Throw(new ResultTestException("first"));
result.Throw(new ResultTestException("second"));
},
typeof(InvalidOperationException), null,
result => result.HasException && (result.Exception is ResultTestException)
);
}
[Test]
public void ConfirmCancel() {
TestFail<int>(
result => {
result.ConfirmCancel();
},
typeof(InvalidOperationException), null,
result => result.HasException && (result.Exception is InvalidOperationException)
);
}
[Test]
public void Return_ConfirmCancel() {
TestFail<int>(
result => {
result.Return(1);
result.ConfirmCancel();
},
typeof(InvalidOperationException), null,
result => result.HasValue && (result.Value == 1)
);
}
[Test]
public void Throw_ConfirmCancel() {
TestFail<int>(
result => {
result.Throw(new ResultTestException());
result.ConfirmCancel();
},
typeof(InvalidOperationException), null,
result => result.HasException && (result.Exception is ResultTestException)
);
}
#endregion
#region --- Helpers ---
private static void Test<T>(bool waitFirst, Action<Result<T>> before, Action<Result<T>> after, bool isSuccess, Type exceptionType, bool isCancel, object cancelOutcome, Action<Result<T>> check) {
int success = 0;
int error = 0;
int canceled = 0;
Result<T> canceldResult = null;
AutoResetEvent wait = new AutoResetEvent(false);
Result<T> result = new Result<T>(TimeSpan.FromSeconds(0.1), TaskEnv.Instantaneous);
if(!waitFirst) {
if(before != null) {
before(result);
}
}
result.WithCleanup(r => { ++canceled; canceldResult = r; wait.Set(); });
result.WhenDone(
v => { ++success; wait.Set(); },
e => { ++error; wait.Set(); }
);
if(waitFirst) {
if(before != null) {
before(result);
}
}
bool waited = wait.WaitOne(TimeSpan.FromSeconds(1), false);
Assert.IsTrue(waited, "result failed to time out");
if(after != null) {
after(result);
}
int expected_success = isSuccess ? 1 : 0;
int expected_error = (exceptionType != null) ? 1 : 0;
int expected_cancel = isCancel ? 1 : 0;
Assert.AreEqual(expected_success, success, string.Format("success was {1}, but expected {0}", expected_success, success));
Assert.AreEqual(expected_error, error, string.Format("error was {1}, but expected {0}", expected_error, error));
Assert.AreEqual(expected_cancel, canceled, string.Format("canceled was {1}, but expected {0}", expected_cancel, canceled));
if(exceptionType != null) {
Assert.IsInstanceOfType(exceptionType, result.Exception, "exception has wrong type");
} else {
Assert.IsNull(result.Exception, "exception is set");
}
if(isCancel) {
if(cancelOutcome == null) {
Assert.IsNull(canceldResult, "canceled result was not null");
} else if(cancelOutcome is Type) {
Assert.IsInstanceOfType((Type)cancelOutcome, canceldResult.Exception, "canceled result exception did not match");
} else {
Assert.AreEqual(cancelOutcome, canceldResult.Value, "canceled result value did not match");
}
}
if(check != null) {
check(result);
}
}
private static void TestFail<T>(Action<Result<T>> callback, Type exceptionType, string exceptionMessage, Predicate<Result<T>> validate) {
Exception ex = null;
var result = new Result<T>();
try {
callback(result);
} catch(Exception e) {
ex = e;
}
if(exceptionType != null) {
Assert.IsNotNull(ex, "no exception was raised; expected " + exceptionType.FullName);
Assert.IsInstanceOfType(exceptionType, ex, "unexpected exception on failed operation");
} else {
Assert.IsNull(ex, "exception thrown");
}
if(exceptionMessage != null) {
Assert.AreEqual(exceptionMessage, ex.Message);
}
if(validate != null) {
Assert.IsTrue(validate(result), "result validation failed");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using DbShell.Driver.Common.Utility;
using System.Runtime.Serialization;
namespace DbShell.Driver.Common.Structure
{
[DataContract]
public class NameWithSchema : IComparable, IFormattable
{
public const string NoQuotePrefix = "(@NOQUOTE)";
/// <summary>
/// Schema name
/// </summary>
public string Schema { get; private set; }
/// <summary>
/// Object name
/// </summary>
public string Name { get; private set; }
public readonly bool HideSchema;
[DataMember(Name ="Schema")]
public string SchemaSerialized
{
get { return Schema; }
set { Schema = value; }
}
[DataMember(Name = "Name")]
public string NameSerialized
{
get { return Name; }
set { Name = value; }
}
public NameWithSchema()
{
}
public NameWithSchema(string schema, string name)
{
if (!String.IsNullOrEmpty(schema)) Schema = schema;
Name = name;
}
public NameWithSchema(string schema, string name, bool hideSchema)
{
if (!String.IsNullOrEmpty(schema)) Schema = schema;
Name = name;
HideSchema = hideSchema;
}
public NameWithSchema GetNameWithHiddenSchema()
{
return new NameWithSchema(Schema, Name, true);
}
public NameWithSchema GetNameWithNullSchema()
{
return new NameWithSchema(Name);
}
public NameWithSchema(string name)
{
if (name == null) return;
if (name.Contains("."))
{
string[] comps = name.Split(new char[] { '.' }, 2);
Schema = comps[0];
Name = comps[1];
}
else
{
Name = name;
}
}
public override bool Equals(object obj)
{
if (obj is NameWithSchema)
{
return this == (NameWithSchema)obj;
}
return base.Equals(obj);
}
public static bool operator ==(NameWithSchema a, NameWithSchema b)
{
if ((object)a == null || (object)b == null) return (object)a == null && (object)b == null;
return a.Name == b.Name && a.Schema == b.Schema;
//if (a.HideSchema && a.Schema != null) a = new NameWithSchema(a.Name);
//if (b.HideSchema && b.Schema != null) b = new NameWithSchema(b.Name);
//return (a.Name ?? "").ToUpper() == (b.Name ?? "").ToUpper() && (a.Schema ?? "").ToUpper() == (b.Schema ?? "").ToUpper();
}
public static bool operator !=(NameWithSchema a, NameWithSchema b)
{
return !(a == b);
}
public override int GetHashCode()
{
if (Name == null) return 0;
return Name.GetHashCode();
//return Name.ToUpper().GetHashCode();
}
public static int Compare(NameWithSchema a, NameWithSchema b)
{
int res = 0;
if (a.Schema == null && b.Schema != null) return -1;
if (a.Schema != null && b.Schema == null) return 1;
if (a.Schema != null && b.Schema != null) res = String.Compare(a.Schema, b.Schema, true);
if (res != 0) return res;
if (a.Name == null && b.Name != null) return -1;
if (a.Name != null && b.Name == null) return 1;
if (a.Name != null && b.Name != null) res = String.Compare(a.Name, b.Name, true);
return res;
}
public void SaveToXml(XmlElement xml)
{
SaveToXml(xml, "");
}
public void SaveToXml(XmlElement xml, string prefix)
{
SaveToXml(xml, prefix + "schema", prefix + "name");
}
public void SaveToXml(XmlElement xml, string schemaattr, string nameattr)
{
if (Schema != null) xml.SetAttribute(schemaattr, Schema);
if (Name != null) xml.SetAttribute(nameattr, Name);
}
public static NameWithSchema LoadFromXml(XmlElement xml, string prefix)
{
return LoadFromXml(xml, prefix + "schema", prefix + "name");
}
public static NameWithSchema LoadFromXml(XmlElement xml, string schemaattr, string nameattr)
{
if (xml == null) return null;
// HACK: aby slo nacist historicke datove archivy
if (nameattr == "name" && xml.HasAttribute("table") && !xml.HasAttribute("name")) nameattr = "table";
if (!xml.HasAttribute(nameattr)) return null;
return new NameWithSchema(xml.GetAttribute(schemaattr), xml.GetAttribute(nameattr));
}
public static NameWithSchema LoadFromXml(XmlElement xml)
{
return LoadFromXml(xml, "");
}
#region IComparable Members
public int CompareTo(object obj)
{
var name2 = obj as NameWithSchema;
if (name2 != null) return NameWithSchema.Compare(this, name2);
return 0;
}
#endregion
public override string ToString()
{
return ToString("M", null);
}
#region IFormattable Members
public string ToString(string format, IFormatProvider formatProvider)
{
switch (format)
{
case "L":
case "M":
case "S":
if (Schema != null && !HideSchema) return Schema + "." + Name;
return Name;
case "F":
if (Schema != null) return Schema + "." + Name;
return Name;
default:
return Name;
}
}
#endregion
public NameWithSchema ToUpper()
{
return new NameWithSchema(Schema != null ? Schema.ToUpper() : null, Name != null ? Name.ToUpper() : null);
}
public NameWithSchema ToLower()
{
return new NameWithSchema(Schema != null ? Schema.ToLower() : null, Name != null ? Name.ToLower() : null);
}
public NameWithSchema GetOnlyCaseDifferentName(IEnumerable<NameWithSchema> choices)
{
if (choices.IndexOfIf(n => n == this) < 0)
{
var up = ToUpper();
var res = choices.FirstOrDefault(n => n.ToUpper() == up);
if (res != null) return res;
}
return this;
}
public static NameWithSchema Parse(string value)
{
if (value == null) return null;
var sident = StructuredIdentifier.Parse(value);
if (sident == null) return null;
var res = sident.ToNameWithSchema();
if (res != null) return res;
int dotPos = value.IndexOf('.');
if (dotPos >= 0) return new NameWithSchema(value.Substring(0, dotPos), value.Substring(dotPos + 1));
else return new NameWithSchema(value);
}
public StructuredIdentifier ToStructuredIdentifier()
{
if (Schema != null && Name != null) return new StructuredIdentifier(new string[] { Schema, Name });
if (Name != null) return new StructuredIdentifier(new string[] { Name });
return null;
}
public string ToStructuredString()
{
return ToStructuredIdentifier().ToString();
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NLog.Targets;
namespace NLog.UnitTests.Config
{
using System;
using System.IO;
using NLog.Config;
using Xunit;
public class IncludeTests : NLogTestBase
{
[Fact]
public void IncludeTest()
{
LogManager.ThrowExceptions = true;
var includeAttrValue = @"included.nlog";
IncludeTest_inner(includeAttrValue, GetTempDir());
}
[Fact]
public void IncludeWildcardTest_relative()
{
var includeAttrValue = @"*.nlog";
IncludeTest_inner(includeAttrValue, GetTempDir());
}
[Fact]
public void IncludeWildcardTest_absolute()
{
var includeAttrValue = @"*.nlog";
var tempPath = GetTempDir();
includeAttrValue = Path.Combine(tempPath, includeAttrValue);
IncludeTest_inner(includeAttrValue, tempPath);
}
private void IncludeTest_inner(string includeAttrValue, string tempDir)
{
Directory.CreateDirectory(tempDir);
CreateConfigFile(tempDir, "included.nlog", @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>");
CreateConfigFile(tempDir, "main.nlog", $@"<nlog>
<include file='{includeAttrValue}' />
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
string fileToLoad = Path.Combine(tempDir, "main.nlog");
try
{
// load main.nlog from the XAP
LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad);
LogManager.GetLogger("A").Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
}
finally
{
if (Directory.Exists(tempDir))
Directory.Delete(tempDir, true);
}
}
[Fact]
public void IncludeNotExistingTest()
{
LogManager.ThrowConfigExceptions = true;
string tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
using (StreamWriter fs = File.CreateText(Path.Combine(tempPath, "main.nlog")))
{
fs.Write(@"<nlog>
<include file='included.nlog' />
</nlog>");
}
string fileToLoad = Path.Combine(tempPath, "main.nlog");
try
{
Assert.Throws<NLogConfigurationException>(() => new XmlLoggingConfiguration(fileToLoad));
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void IncludeNotExistingIgnoredTest()
{
var tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
var config = @"<nlog>
<include file='included-notpresent.nlog' ignoreErrors='true' />
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
CreateConfigFile(tempPath, "main.nlog", config);
string fileToLoad = Path.Combine(tempPath, "main.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad);
LogManager.GetLogger("A").Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void IncludeNotExistingIgnoredTest_DoesNotThrow()
{
LogManager.ThrowExceptions = true;
var tempPath = GetTempDir();
Directory.CreateDirectory(tempPath);
var config = @"<nlog>
<include file='included-notpresent.nlog' ignoreErrors='true' />
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
CreateConfigFile(tempPath, "main.nlog", config);
string fileToLoad = Path.Combine(tempPath, "main.nlog");
var ex = Record.Exception(() => new XmlLoggingConfiguration(fileToLoad));
Assert.Null(ex);
}
/// <summary>
/// Create config file in dir
/// </summary>
/// <param name="tempPath"></param>
/// <param name="filename"></param>
/// <param name="config"></param>
private static void CreateConfigFile(string tempPath, string filename, string config)
{
using (var fs = File.CreateText(Path.Combine(tempPath, filename)))
{
fs.Write(config);
}
}
private static string GetTempDir()
{
return Path.Combine(Path.GetTempPath(), Guid.NewGuid().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.
// Summary:
// Implements the exhaustive task cancel and wait scenarios.
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics; // for Stopwatch
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace System.Threading.Tasks.Tests.CancelWait
{
/// <summary>
/// Test class
/// </summary>
public sealed class TaskCancelWaitTest
{
#region Private Fields
private API _api; // the API_CancelWait to be tested
private WaitBy _waitBy; // the format of Wait
private int _waitTimeout; // the timeout in ms to be waited
private TaskInfo _taskTree; // the _taskTree to track child task cancellation option
private static readonly int s_deltaTimeOut = 10;
private bool _taskCompleted; // result to record the Wait(timeout) return value
private AggregateException _caughtException; // exception thrown during wait
private CountdownEvent _countdownEvent; // event to signal the main thread that the whole task tree has been created
#endregion
/// <summary>
/// .ctor
/// </summary>
public TaskCancelWaitTest(TestParameters parameters)
{
_api = parameters.API_CancelWait;
_waitBy = parameters.WaitBy_CancelWait;
_waitTimeout = parameters.WaitTime;
_taskTree = parameters.RootNode;
_countdownEvent = new CountdownEvent(CaluateLeafNodes(_taskTree));
}
#region Helper Methods
/// <summary>
/// The method that performs the tests
/// Depending on the inputs different test code paths will be exercised
/// </summary>
internal void RealRun()
{
TaskScheduler tm = TaskScheduler.Default;
CreateTask(tm, _taskTree);
// wait the whole task tree to be created
_countdownEvent.Wait();
Stopwatch sw = Stopwatch.StartNew();
try
{
switch (_api)
{
case API.Cancel:
_taskTree.CancellationTokenSource.Cancel();
_taskTree.Task.Wait();
break;
case API.Wait:
switch (_waitBy)
{
case WaitBy.None:
_taskTree.Task.Wait();
_taskCompleted = true;
break;
case WaitBy.Millisecond:
_taskCompleted = _taskTree.Task.Wait(_waitTimeout);
break;
case WaitBy.TimeSpan:
_taskCompleted = _taskTree.Task.Wait(new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
}
}
catch (AggregateException exp)
{
_caughtException = exp.Flatten();
}
finally
{
sw.Stop();
}
if (_waitTimeout != -1)
{
long delta = sw.ElapsedMilliseconds - ((long)_waitTimeout + s_deltaTimeOut);
if (delta > 0)
{
Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
Debug.WriteLine("WaitTime= {0} ms, ElapsedTime= {1} ms, Allowed Discrepancy = {2} ms", _waitTimeout, sw.ElapsedMilliseconds, s_deltaTimeOut);
Debug.WriteLine("Delta= {0} ms", delta);
}
else
{
var delaytask = Task.Delay((int)Math.Abs(delta)); // give delay to allow Context being collected before verification
delaytask.Wait();
}
}
Verify();
_countdownEvent.Dispose();
}
/// <summary>
/// recursively walk the tree and attach the tasks to the nodes
/// </summary>
private void CreateTask(TaskScheduler tm, TaskInfo treeNode)
{
treeNode.Task = Task.Factory.StartNew(
delegate (object o)
{
TaskInfo current = (TaskInfo)o;
if (current.IsLeaf)
{
lock (_countdownEvent)
{
if (!_countdownEvent.IsSet)
_countdownEvent.Signal();
}
}
else
{
// create children tasks
foreach (TaskInfo child in current.Children)
{
if (child.IsRespectParentCancellation)
{
//
// if child to respect parent cancellation we need to wire a linked token
//
child.CancellationToken =
CancellationTokenSource.CreateLinkedTokenSource(treeNode.CancellationToken, child.CancellationToken).Token;
}
CreateTask(tm, child);
}
}
if (current.CancelChildren)
{
try
{
foreach (TaskInfo child in current.Children)
{
child.CancellationTokenSource.Cancel();
}
}
finally
{
lock (_countdownEvent)
{
// stop the tree creation and let the main thread proceed
if (!_countdownEvent.IsSet)
{
_countdownEvent.Signal(_countdownEvent.CurrentCount);
}
}
}
}
// run the workload
current.RunWorkload();
}, treeNode, treeNode.CancellationToken, treeNode.Option, tm);
}
/// <summary>
/// Walk the tree and calculates the tree nodes count
/// </summary>
/// <param name="tree"></param>
private int CaluateLeafNodes(TaskInfo tree)
{
if (tree.IsLeaf)
return 1;
int sum = 0;
foreach (TaskInfo child in tree.Children)
sum += CaluateLeafNodes(child);
return sum;
}
/// <summary>
/// Verification method
/// </summary>
private void Verify()
{
switch (_api)
{
//root task had the token source cancelled
case API.Cancel:
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyCancel(current);
VerifyResult(current);
});
Assert.Null(_caughtException);
break;
//root task was calling wait
case API.Wait:
//will be true if the root cancelled itself - through its workload
if (_taskTree.CancellationToken.IsCancellationRequested)
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyTaskCanceledException(current);
});
}
else
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyWait(current);
VerifyResult(current);
});
}
break;
default:
throw new ArgumentOutOfRangeException(string.Format("unknown API_CancelWait of {0}", _api));
}
}
/// <summary>
/// Cancel Verification
/// </summary>
private void VerifyCancel(TaskInfo current)
{
TaskInfo ti = current;
if (current.Parent == null)
{
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Root task must be cancel-requested"));
else if (_countdownEvent.IsSet && ti.Task.IsCanceled)
Assert.True(false, string.Format("Root task should not be cancelled when the whole tree has been created"));
}
else if (current.Parent.CancelChildren)
{
// need to make sure the parent task at least called .Cancel() on the child
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task which has been explicitly cancel-requested either by parent must have CancellationRequested set as true"));
}
else if (ti.IsRespectParentCancellation)
{
if (ti.CancellationToken.IsCancellationRequested != current.Parent.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task with RespectParentCancellationcontract is broken"));
}
else
{
if (ti.CancellationToken.IsCancellationRequested || ti.Task.IsCanceled)
Assert.True(false, string.Format("Inner non-directly canceled task which opts out RespectParentCancellationshould not be cancelled"));
}
// verify IsCanceled indicate successfully dequeued based on the observing that
// - Thread is recorded the first thing in the RunWorkload from user delegate
//if (ti.Task.IsCompleted && (ti.Thread == null) != ti.Task.IsCanceled)
// Assert.Fail("IsCanceled contract is broken -- completed task which has the delegate executed can't have IsCanceled return true")
}
/// <summary>
/// Verify the Wait code path
/// </summary>
private void VerifyWait(TaskInfo current)
{
TaskInfo ti = current;
TaskInfo parent = current.Parent;
if (_taskCompleted)
{
if (parent == null)
{
Assert.True(ti.Task.IsCompleted, "Root task must complete");
}
else if (parent != null && parent.Task.IsCompleted)
{
if ((ti.Option & TaskCreationOptions.AttachedToParent) != 0
&& !ti.Task.IsCompleted)
{
Assert.True(false, string.Format("Inner attached task must complete"));
}
}
}
}
private void VerifyTaskCanceledException(TaskInfo current)
{
bool expCaught;
TaskInfo ti = current;
//a task will get into cancelled state only if:
//1.Its token was cancelled before as its action to get invoked
//2.The token was cancelled before the task's action to finish, task observed the cancelled token and threw OCE(token)
if (ti.Task.Status == TaskStatus.Canceled)
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.True(expCaught, "expected TaskCanceledException in Task.Name = Task " + current.Name + " NOT caught");
}
else
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.False(expCaught, "NON-expected TaskCanceledException in Task.Name = Task " + current.Name + " caught");
}
}
private void VerifyResult(TaskInfo current)
{
TaskInfo ti = current;
WorkloadType workType = ti.WorkType;
if (workType == WorkloadType.Exceptional && _api != API.Cancel)
{
bool expCaught = FindException((ex) =>
{
TPLTestException expectedExp = ex as TPLTestException;
return expectedExp != null && expectedExp.FromTaskId == ti.Task.Id;
});
if (!expCaught)
Assert.True(false, string.Format("expected TPLTestException in Task.Name = Task{0} NOT caught", current.Name));
}
else
{
if (ti.Task.Exception != null && _api == API.Wait)
Assert.True(false, string.Format("UNEXPECTED exception in Task.Name = Task{0} caught. Exception: {1}", current.Name, ti.Task.Exception));
if (ti.Task.IsCanceled && ti.Result != -42)
{
//this means that the task was not scheduled - it was cancelled or it is still in the queue
//-42 = UNINITIALED_RESULT
Assert.True(false, string.Format("Result must remain uninitialized for unstarted task"));
}
else if (ti.Task.IsCompleted)
{
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
if (ti.Result < minLimit || ti.Result > maxLimit)
Assert.True(ti.Task.IsCanceled || ti.Task.IsFaulted,
string.Format(
"Expected Result to lie between {0} and {1} for completed task. Actual Result {2}. Using n={3} IsCanceled={4}",
minLimit,
maxLimit,
ti.Result,
workType,
ti.Task.IsCanceled));
}
}
}
/// <summary>
/// Verify the _caughtException against a custom predicate
/// </summary>
private bool FindException(Predicate<Exception> exceptionPred)
{
if (_caughtException == null)
return false; // not caught any exceptions
foreach (Exception ex in _caughtException.InnerExceptions)
{
if (exceptionPred(ex))
return true;
}
return false;
}
#endregion
}
#region Helper Classes / Enums
public class TestParameters
{
public readonly int WaitTime;
public readonly WaitBy WaitBy_CancelWait;
public readonly TaskInfo RootNode;
public readonly API API_CancelWait;
public TestParameters(TaskInfo rootNode, API api_CancelWait, WaitBy waitBy_CancelWait, int waitTime)
{
WaitBy_CancelWait = waitBy_CancelWait;
WaitTime = waitTime;
RootNode = rootNode;
API_CancelWait = api_CancelWait;
}
}
/// <summary>
/// The Tree node Data type
///
/// While the tree is not restricted to this data type
/// the implemented tests are using the TaskInfo_CancelWait data type for their scenarios
/// </summary>
public class TaskInfo
{
private static TaskCreationOptions s_DEFAULT_OPTION = TaskCreationOptions.AttachedToParent;
private static double s_UNINITIALED_RESULT = -42;
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString)
{
Children = new LinkedList<TaskInfo>();
Result = s_UNINITIALED_RESULT;
Option = s_DEFAULT_OPTION;
Name = TaskInfo_CancelWaitName;
WorkType = workType;
Parent = parent;
CancelChildren = false;
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
if (string.IsNullOrEmpty(optionsString))
return;
//
// Parse Task CreationOptions, if RespectParentCancellation we would want to acknowledge that
// and passed the remaining options for creation
//
string[] options = optionsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int index = -1;
for (int i = 0; i < options.Length; i++)
{
string o = options[i].Trim(); // remove any whitespace.
options[i] = o;
if (o.Equals("RespectParentCancellation", StringComparison.OrdinalIgnoreCase))
{
IsRespectParentCancellation = true;
index = i;
}
}
if (index != -1)
{
string[] temp = new string[options.Length - 1];
int excludeIndex = index + 1;
Array.Copy(options, 0, temp, 0, index);
int leftToCopy = options.Length - excludeIndex;
Array.Copy(options, excludeIndex, temp, index, leftToCopy);
options = temp;
}
if (options.Length > 0)
{
TaskCreationOptions parsedOptions;
string joinedOptions = string.Join(",", options);
bool parsed = Enum.TryParse<TaskCreationOptions>(joinedOptions, out parsedOptions);
if (!parsed)
throw new NotSupportedException("could not parse the options string: " + joinedOptions);
Option = parsedOptions;
}
}
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString, bool cancelChildren)
: this(parent, TaskInfo_CancelWaitName, workType, optionsString)
{
CancelChildren = cancelChildren;
}
#region Properties
/// <summary>
/// The task associated with the current node
/// </summary>
public Task Task { get; set; }
/// <summary>
/// LinkedList representing the children of the current node
/// </summary>
public LinkedList<TaskInfo> Children { get; set; }
/// <summary>
/// Bool flag indicating is the current node is a leaf
/// </summary>
public bool IsLeaf
{
get { return Children.Count == 0; }
}
/// <summary>
/// Current node Parent
/// </summary>
public TaskInfo Parent { get; set; }
/// <summary>
/// Current node Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// TaskCreation option of task associated with the current node
/// </summary>
public TaskCreationOptions Option { get; private set; }
/// <summary>
/// WorkloadType_CancelWait of task associated with the current node
/// </summary>
public WorkloadType WorkType { get; private set; }
/// <summary>
/// bool for indicating if the current tasks should initiate its children cancellation
/// </summary>
public bool CancelChildren { get; private set; }
/// <summary>
/// While a tasks is correct execute a result is produced
/// this is the result
/// </summary>
public double Result { get; private set; }
/// <summary>
/// The token associated with the current node's task
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Every node has a cancellation source - its token participate in the task creation
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>
/// bool indicating if the children respect parent cancellation
/// If true - the children cancellation token will be linkewd with the parent cancellation
/// so is the parent will get cancelled the children will get as well
/// </summary>
public bool IsRespectParentCancellation { get; private set; }
#endregion
#region Helper Methods
/// <summary>
/// Recursively traverse the tree and compare the current node using the predicate
/// </summary>
/// <param name="predicate">the predicate</param>
/// <param name="report"></param>
/// <returns></returns>
public void Traversal(Action<TaskInfo> predicate)
{
// check current data. If it fails check, an exception is thrown and it stops checking.
// check children
foreach (TaskInfo child in Children)
{
predicate(child);
child.Traversal(predicate);
}
}
/// <summary>
/// The Task workload execution
/// </summary>
public void RunWorkload()
{
//Thread = Thread.CurrentThread;
if (WorkType == WorkloadType.Exceptional)
{
ThrowException();
}
else if (WorkType == WorkloadType.Cancelled)
{
CancelSelf(this.CancellationTokenSource, this.CancellationToken);
}
else
{
// run the workload
if (Result == s_UNINITIALED_RESULT)
{
Result = ZetaSequence((int)WorkType);
}
else // task re-entry, mark it failed
{
Result = s_UNINITIALED_RESULT;
}
}
}
public static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Cancel self workload. The CancellationToken has been wired such that the source passed to this method
/// is a source that can actually causes the Task CancellationToken to be canceled. The source could be the
/// Token's original source, or one of the sources in case of Linked Tokens
/// </summary>
/// <param name="cts"></param>
public static void CancelSelf(CancellationTokenSource cts, CancellationToken ct)
{
cts.Cancel();
throw new OperationCanceledException(ct);
}
public static void ThrowException()
{
throw new TPLTestException();
}
internal void AddChildren(TaskInfo[] children)
{
foreach (var child in children)
Children.AddLast(child);
}
#endregion
}
public enum API
{
Cancel,
Wait,
}
/// <summary>
/// Waiting type
/// </summary>
public enum WaitBy
{
None,
TimeSpan,
Millisecond,
}
/// <summary>
/// Every task has an workload associated
/// These are the workload types used in the task tree
/// The workload is not common for the whole tree - Every node can have its own workload
/// </summary>
public enum WorkloadType
{
Exceptional = -2,
Cancelled = -1,
VeryLight = 100, // the number is the N input to the ZetaSequence workload
Light = 200,
Medium = 400,
Heavy = 800,
VeryHeavy = 1600,
}
#endregion
}
| |
#nullable disable
using System;
using System.IO;
namespace SharpCompress.Compressors.LZMA.LZ
{
internal sealed class BinTree : InWindow
{
private UInt32 _cyclicBufferPos;
private UInt32 _cyclicBufferSize;
private UInt32 _matchMaxLen;
private UInt32[] _son;
private UInt32[] _hash;
private UInt32 _cutValue = 0xFF;
private UInt32 _hashMask;
private UInt32 _hashSizeSum;
private bool _hashArray = true;
private const UInt32 K_HASH2_SIZE = 1 << 10;
private const UInt32 K_HASH3_SIZE = 1 << 16;
private const UInt32 K_BT2_HASH_SIZE = 1 << 16;
private const UInt32 K_START_MAX_LEN = 1;
private const UInt32 K_HASH3_OFFSET = K_HASH2_SIZE;
private const UInt32 K_EMPTY_HASH_VALUE = 0;
private const UInt32 K_MAX_VAL_FOR_NORMALIZE = ((UInt32)1 << 31) - 1;
private UInt32 _kNumHashDirectBytes;
private UInt32 _kMinMatchCheck = 4;
private UInt32 _kFixHashSize = K_HASH2_SIZE + K_HASH3_SIZE;
public void SetType(int numHashBytes)
{
_hashArray = (numHashBytes > 2);
if (_hashArray)
{
_kNumHashDirectBytes = 0;
_kMinMatchCheck = 4;
_kFixHashSize = K_HASH2_SIZE + K_HASH3_SIZE;
}
else
{
_kNumHashDirectBytes = 2;
_kMinMatchCheck = 2 + 1;
_kFixHashSize = 0;
}
}
public new void SetStream(Stream stream)
{
base.SetStream(stream);
}
public new void ReleaseStream()
{
base.ReleaseStream();
}
public new void Init()
{
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
{
_hash[i] = K_EMPTY_HASH_VALUE;
}
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
public new void MovePos()
{
if (++_cyclicBufferPos >= _cyclicBufferSize)
{
_cyclicBufferPos = 0;
}
base.MovePos();
if (_pos == K_MAX_VAL_FOR_NORMALIZE)
{
Normalize();
}
}
public new Byte GetIndexByte(Int32 index)
{
return base.GetIndexByte(index);
}
public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{
return base.GetMatchLen(index, distance, limit);
}
public new UInt32 GetNumAvailableBytes()
{
return base.GetNumAvailableBytes();
}
public void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > K_MAX_VAL_FOR_NORMALIZE - 256)
{
throw new Exception();
}
_cutValue = 16 + (matchMaxLen >> 1);
UInt32 windowReservSize = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize);
_matchMaxLen = matchMaxLen;
UInt32 cyclicBufferSize = historySize + 1;
if (_cyclicBufferSize != cyclicBufferSize)
{
_son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2];
}
UInt32 hs = K_BT2_HASH_SIZE;
if (_hashArray)
{
hs = historySize - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
{
hs >>= 1;
}
_hashMask = hs;
hs++;
hs += _kFixHashSize;
}
if (hs != _hashSizeSum)
{
_hash = new UInt32[_hashSizeSum = hs];
}
}
public UInt32 GetMatches(UInt32[] distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
{
lenLimit = _matchMaxLen;
}
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < _kMinMatchCheck)
{
MovePos();
return 0;
}
}
UInt32 offset = 0;
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 maxLen = K_START_MAX_LEN; // to avoid items for len < hashSize;
UInt32 hashValue, hash2Value = 0, hash3Value = 0;
if (_hashArray)
{
UInt32 temp = Crc.TABLE[_bufferBase[cur]] ^ _bufferBase[cur + 1];
hash2Value = temp & (K_HASH2_SIZE - 1);
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
hash3Value = temp & (K_HASH3_SIZE - 1);
hashValue = (temp ^ (Crc.TABLE[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
{
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
}
UInt32 curMatch = _hash[_kFixHashSize + hashValue];
if (_hashArray)
{
UInt32 curMatch2 = _hash[hash2Value];
UInt32 curMatch3 = _hash[K_HASH3_OFFSET + hash3Value];
_hash[hash2Value] = _pos;
_hash[K_HASH3_OFFSET + hash3Value] = _pos;
if (curMatch2 > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur])
{
distances[offset++] = maxLen = 2;
distances[offset++] = _pos - curMatch2 - 1;
}
}
if (curMatch3 > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur])
{
if (curMatch3 == curMatch2)
{
offset -= 2;
}
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
}
if (offset != 0 && curMatch2 == curMatch)
{
offset -= 2;
maxLen = K_START_MAX_LEN;
}
}
_hash[_kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = _kNumHashDirectBytes;
if (_kNumHashDirectBytes != 0)
{
if (curMatch > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch + _kNumHashDirectBytes] !=
_bufferBase[cur + _kNumHashDirectBytes])
{
distances[offset++] = maxLen = _kNumHashDirectBytes;
distances[offset++] = _pos - curMatch - 1;
}
}
}
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = K_EMPTY_HASH_VALUE;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos)
? (_cyclicBufferPos - delta)
: (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
{
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
{
break;
}
}
if (maxLen < len)
{
distances[offset++] = maxLen = len;
distances[offset++] = delta - 1;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
return offset;
}
public void Skip(UInt32 num)
{
do
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
{
lenLimit = _matchMaxLen;
}
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < _kMinMatchCheck)
{
MovePos();
continue;
}
}
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 hashValue;
if (_hashArray)
{
UInt32 temp = Crc.TABLE[_bufferBase[cur]] ^ _bufferBase[cur + 1];
UInt32 hash2Value = temp & (K_HASH2_SIZE - 1);
_hash[hash2Value] = _pos;
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
UInt32 hash3Value = temp & (K_HASH3_SIZE - 1);
_hash[K_HASH3_OFFSET + hash3Value] = _pos;
hashValue = (temp ^ (Crc.TABLE[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
{
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
}
UInt32 curMatch = _hash[_kFixHashSize + hashValue];
_hash[_kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = _kNumHashDirectBytes;
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = K_EMPTY_HASH_VALUE;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos)
? (_cyclicBufferPos - delta)
: (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
{
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
{
break;
}
}
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
}
while (--num != 0);
}
private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
{
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
{
value = K_EMPTY_HASH_VALUE;
}
else
{
value -= subValue;
}
items[i] = value;
}
}
private void Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
NormalizeLinks(_hash, _hashSizeSum, subValue);
ReduceOffsets((Int32)subValue);
}
public void SetCutValue(UInt32 cutValue)
{
_cutValue = cutValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
using Orleans.Metadata;
using Orleans.Runtime.Providers;
using Orleans.Runtime.Utilities;
namespace Orleans.Runtime.Metadata
{
internal class ClusterManifestProvider : IClusterManifestProvider, IAsyncDisposable, IDisposable, ILifecycleParticipant<ISiloLifecycle>
{
private readonly SiloAddress _localSiloAddress;
private readonly ILogger<ClusterManifestProvider> _logger;
private readonly IServiceProvider _services;
private readonly IClusterMembershipService _clusterMembershipService;
private readonly IFatalErrorHandler _fatalErrorHandler;
private readonly CancellationTokenSource _cancellation = new CancellationTokenSource();
private readonly AsyncEnumerable<ClusterManifest> _updates;
private ClusterManifest _current;
private Task _runTask;
public ClusterManifestProvider(
ILocalSiloDetails localSiloDetails,
SiloManifestProvider siloManifestProvider,
ClusterMembershipService clusterMembershipService,
IFatalErrorHandler fatalErrorHandler,
ILogger<ClusterManifestProvider> logger,
IServiceProvider services)
{
_localSiloAddress = localSiloDetails.SiloAddress;
_logger = logger;
_services = services;
_clusterMembershipService = clusterMembershipService;
_fatalErrorHandler = fatalErrorHandler;
this.LocalGrainManifest = siloManifestProvider.SiloManifest;
_current = new ClusterManifest(
MajorMinorVersion.Zero,
ImmutableDictionary.CreateRange(new[] { new KeyValuePair<SiloAddress, GrainManifest>(localSiloDetails.SiloAddress, this.LocalGrainManifest) }),
ImmutableArray.Create(this.LocalGrainManifest));
_updates = new AsyncEnumerable<ClusterManifest>(
(previous, proposed) => previous.Version <= MajorMinorVersion.Zero || proposed.Version > previous.Version,
_current)
{
OnPublished = update => Interlocked.Exchange(ref _current, update)
};
}
public ClusterManifest Current => _current;
public IAsyncEnumerable<ClusterManifest> Updates => _updates;
public GrainManifest LocalGrainManifest { get; }
private async Task ProcessMembershipUpdates()
{
try
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Starting to process membership updates");
}
var cancellation = _cancellation.Token;
await foreach (var _ in _clusterMembershipService.MembershipUpdates.WithCancellation(cancellation))
{
while (true)
{
var membershipSnapshot = _clusterMembershipService.CurrentSnapshot;
var success = await this.UpdateManifest(membershipSnapshot);
if (success || cancellation.IsCancellationRequested)
{
break;
}
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
catch (Exception exception) when (_fatalErrorHandler.IsUnexpected(exception))
{
_fatalErrorHandler.OnFatalException(this, nameof(ProcessMembershipUpdates), exception);
}
finally
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Stopped processing membership updates");
}
}
}
private async Task<bool> UpdateManifest(ClusterMembershipSnapshot clusterMembership)
{
var existingManifest = _current;
var builder = existingManifest.Silos.ToBuilder();
var modified = false;
// First, remove defunct entries.
foreach (var entry in existingManifest.Silos)
{
var address = entry.Key;
var status = clusterMembership.GetSiloStatus(address);
if (address.Equals(_localSiloAddress))
{
// The local silo is always present in the manifest.
continue;
}
if (status == SiloStatus.None || status == SiloStatus.Dead)
{
builder.Remove(address);
modified = true;
}
}
// Next, fill missing entries.
var tasks = new List<Task<(SiloAddress Key, GrainManifest Value, Exception Exception)>>();
foreach (var entry in clusterMembership.Members)
{
var member = entry.Value;
if (member.SiloAddress.Equals(_localSiloAddress))
{
// The local silo is always present in the manifest.
continue;
}
if (existingManifest.Silos.ContainsKey(member.SiloAddress))
{
// Manifest has already been retrieved for the cluster member.
continue;
}
if (member.Status != SiloStatus.Active)
{
// If the member is not yet active, it may not be ready to process requests.
continue;
}
tasks.Add(GetManifest(member.SiloAddress));
async Task<(SiloAddress, GrainManifest, Exception)> GetManifest(SiloAddress siloAddress)
{
try
{
// Get the manifest from the remote silo.
var grainFactory = _services.GetRequiredService<IInternalGrainFactory>();
var remoteManifestProvider = grainFactory.GetSystemTarget<ISiloManifestSystemTarget>(Constants.ManifestProviderType, member.SiloAddress);
var manifest = await remoteManifestProvider.GetSiloManifest();
return (siloAddress, manifest, null);
}
catch (Exception exception)
{
return (siloAddress, null, exception);
}
}
}
var fetchSuccess = true;
await Task.WhenAll(tasks);
foreach (var task in tasks)
{
var result = await task;
if (result.Exception is Exception exception)
{
fetchSuccess = false;
_logger.LogWarning(exception, "Error retrieving silo manifest for silo {SiloAddress}", result.Key);
}
else
{
modified = true;
builder[result.Key] = result.Value;
}
}
// Regardless of success or failure, update the manifest if it has been modified.
var version = new MajorMinorVersion(clusterMembership.Version.Value, existingManifest.Version.Minor + 1);
if (modified)
{
return _updates.TryPublish(new ClusterManifest(version, builder.ToImmutable(), builder.Values.ToImmutableArray())) && fetchSuccess;
}
return fetchSuccess;
}
private Task StartAsync(CancellationToken _)
{
_runTask = Task.Run(ProcessMembershipUpdates);
return Task.CompletedTask;
}
private Task Initialize(CancellationToken _)
{
var catalog = _services.GetRequiredService<Catalog>();
catalog.RegisterSystemTarget(ActivatorUtilities.CreateInstance<ClusterManifestSystemTarget>(_services));
return Task.CompletedTask;
}
private async Task StopAsync(CancellationToken cancellationToken)
{
_cancellation.Cancel();
if (_runTask is Task task)
{
await task;
}
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(
nameof(ClusterManifestProvider),
ServiceLifecycleStage.RuntimeServices,
Initialize,
_ => Task.CompletedTask);
lifecycle.Subscribe(
nameof(ClusterManifestProvider),
ServiceLifecycleStage.RuntimeGrainServices,
StartAsync,
StopAsync);
}
public async ValueTask DisposeAsync()
{
await this.StopAsync(CancellationToken.None);
}
public void Dispose()
{
_cancellation.Cancel();
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// CreateMobileReservation
/// </summary>
[DataContract]
public partial class CreateMobileReservation : IEquatable<CreateMobileReservation>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateMobileReservation" /> class.
/// </summary>
[JsonConstructorAttribute]
protected CreateMobileReservation() { }
/// <summary>
/// Initializes a new instance of the <see cref="CreateMobileReservation" /> class.
/// </summary>
/// <param name="ReservationTime">ReservationTime (required).</param>
/// <param name="GroupSize">GroupSize (required).</param>
/// <param name="RestaurantId">RestaurantId.</param>
/// <param name="CustomerName">CustomerName.</param>
/// <param name="PhoneNumber">PhoneNumber.</param>
/// <param name="Email">Email.</param>
/// <param name="Areas">Areas.</param>
/// <param name="SpecialRequests">SpecialRequests.</param>
/// <param name="AboutGuestNotes">AboutGuestNotes.</param>
/// <param name="Language">Language.</param>
/// <param name="HighChair">HighChair.</param>
/// <param name="Stroller">Stroller.</param>
/// <param name="Party">Party.</param>
/// <param name="Booth">Booth.</param>
/// <param name="HighTop">HighTop.</param>
/// <param name="Table">Table.</param>
/// <param name="DepositToken">DepositToken.</param>
/// <param name="PartyTypes">PartyTypes.</param>
/// <param name="CustomerProfile">CustomerProfile.</param>
public CreateMobileReservation(DateTimeOffset? ReservationTime = null, int? GroupSize = null, int? RestaurantId = null, string CustomerName = null, string PhoneNumber = null, string Email = null, string Areas = null, string SpecialRequests = null, string AboutGuestNotes = null, string Language = null, bool? HighChair = null, bool? Stroller = null, bool? Party = null, bool? Booth = null, bool? HighTop = null, bool? Table = null, string DepositToken = null, List<string> PartyTypes = null, ProfileData CustomerProfile = null)
{
// to ensure "ReservationTime" is required (not null)
if (ReservationTime == null)
{
throw new InvalidDataException("ReservationTime is a required property for CreateMobileReservation and cannot be null");
}
else
{
this.ReservationTime = ReservationTime;
}
// to ensure "GroupSize" is required (not null)
if (GroupSize == null)
{
throw new InvalidDataException("GroupSize is a required property for CreateMobileReservation and cannot be null");
}
else
{
this.GroupSize = GroupSize;
}
this.RestaurantId = RestaurantId;
this.CustomerName = CustomerName;
this.PhoneNumber = PhoneNumber;
this.Email = Email;
this.Areas = Areas;
this.SpecialRequests = SpecialRequests;
this.AboutGuestNotes = AboutGuestNotes;
this.Language = Language;
this.HighChair = HighChair;
this.Stroller = Stroller;
this.Party = Party;
this.Booth = Booth;
this.HighTop = HighTop;
this.Table = Table;
this.DepositToken = DepositToken;
this.PartyTypes = PartyTypes;
this.CustomerProfile = CustomerProfile;
}
/// <summary>
/// Gets or Sets ReservationTime
/// </summary>
[DataMember(Name="reservationTime", EmitDefaultValue=true)]
public DateTimeOffset? ReservationTime { get; set; }
/// <summary>
/// Gets or Sets GroupSize
/// </summary>
[DataMember(Name="groupSize", EmitDefaultValue=true)]
public int? GroupSize { get; set; }
/// <summary>
/// Gets or Sets RestaurantId
/// </summary>
[DataMember(Name="restaurantId", EmitDefaultValue=true)]
public int? RestaurantId { get; set; }
/// <summary>
/// Gets or Sets CustomerName
/// </summary>
[DataMember(Name="customerName", EmitDefaultValue=true)]
public string CustomerName { get; set; }
/// <summary>
/// Gets or Sets PhoneNumber
/// </summary>
[DataMember(Name="phoneNumber", EmitDefaultValue=true)]
public string PhoneNumber { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=true)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Areas
/// </summary>
[DataMember(Name="areas", EmitDefaultValue=true)]
public string Areas { get; set; }
/// <summary>
/// Gets or Sets SpecialRequests
/// </summary>
[DataMember(Name="specialRequests", EmitDefaultValue=true)]
public string SpecialRequests { get; set; }
/// <summary>
/// Gets or Sets AboutGuestNotes
/// </summary>
[DataMember(Name="aboutGuestNotes", EmitDefaultValue=true)]
public string AboutGuestNotes { get; set; }
/// <summary>
/// Gets or Sets Language
/// </summary>
[DataMember(Name="language", EmitDefaultValue=true)]
public string Language { get; set; }
/// <summary>
/// Gets or Sets HighChair
/// </summary>
[DataMember(Name="highChair", EmitDefaultValue=true)]
public bool? HighChair { get; set; }
/// <summary>
/// Gets or Sets Stroller
/// </summary>
[DataMember(Name="stroller", EmitDefaultValue=true)]
public bool? Stroller { get; set; }
/// <summary>
/// Gets or Sets Party
/// </summary>
[DataMember(Name="party", EmitDefaultValue=true)]
public bool? Party { get; set; }
/// <summary>
/// Gets or Sets Booth
/// </summary>
[DataMember(Name="booth", EmitDefaultValue=true)]
public bool? Booth { get; set; }
/// <summary>
/// Gets or Sets HighTop
/// </summary>
[DataMember(Name="highTop", EmitDefaultValue=true)]
public bool? HighTop { get; set; }
/// <summary>
/// Gets or Sets Table
/// </summary>
[DataMember(Name="table", EmitDefaultValue=true)]
public bool? Table { get; set; }
/// <summary>
/// Gets or Sets DepositToken
/// </summary>
[DataMember(Name="depositToken", EmitDefaultValue=true)]
public string DepositToken { get; set; }
/// <summary>
/// Gets or Sets PartyTypes
/// </summary>
[DataMember(Name="partyTypes", EmitDefaultValue=true)]
public List<string> PartyTypes { get; set; }
/// <summary>
/// Gets or Sets CustomerProfile
/// </summary>
[DataMember(Name="customerProfile", EmitDefaultValue=true)]
public ProfileData CustomerProfile { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CreateMobileReservation {\n");
sb.Append(" ReservationTime: ").Append(ReservationTime).Append("\n");
sb.Append(" GroupSize: ").Append(GroupSize).Append("\n");
sb.Append(" RestaurantId: ").Append(RestaurantId).Append("\n");
sb.Append(" CustomerName: ").Append(CustomerName).Append("\n");
sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Areas: ").Append(Areas).Append("\n");
sb.Append(" SpecialRequests: ").Append(SpecialRequests).Append("\n");
sb.Append(" AboutGuestNotes: ").Append(AboutGuestNotes).Append("\n");
sb.Append(" Language: ").Append(Language).Append("\n");
sb.Append(" HighChair: ").Append(HighChair).Append("\n");
sb.Append(" Stroller: ").Append(Stroller).Append("\n");
sb.Append(" Party: ").Append(Party).Append("\n");
sb.Append(" Booth: ").Append(Booth).Append("\n");
sb.Append(" HighTop: ").Append(HighTop).Append("\n");
sb.Append(" Table: ").Append(Table).Append("\n");
sb.Append(" DepositToken: ").Append(DepositToken).Append("\n");
sb.Append(" PartyTypes: ").Append(PartyTypes).Append("\n");
sb.Append(" CustomerProfile: ").Append(CustomerProfile).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CreateMobileReservation);
}
/// <summary>
/// Returns true if CreateMobileReservation instances are equal
/// </summary>
/// <param name="other">Instance of CreateMobileReservation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CreateMobileReservation other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ReservationTime == other.ReservationTime ||
this.ReservationTime != null &&
this.ReservationTime.Equals(other.ReservationTime)
) &&
(
this.GroupSize == other.GroupSize ||
this.GroupSize != null &&
this.GroupSize.Equals(other.GroupSize)
) &&
(
this.RestaurantId == other.RestaurantId ||
this.RestaurantId != null &&
this.RestaurantId.Equals(other.RestaurantId)
) &&
(
this.CustomerName == other.CustomerName ||
this.CustomerName != null &&
this.CustomerName.Equals(other.CustomerName)
) &&
(
this.PhoneNumber == other.PhoneNumber ||
this.PhoneNumber != null &&
this.PhoneNumber.Equals(other.PhoneNumber)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.Areas == other.Areas ||
this.Areas != null &&
this.Areas.Equals(other.Areas)
) &&
(
this.SpecialRequests == other.SpecialRequests ||
this.SpecialRequests != null &&
this.SpecialRequests.Equals(other.SpecialRequests)
) &&
(
this.AboutGuestNotes == other.AboutGuestNotes ||
this.AboutGuestNotes != null &&
this.AboutGuestNotes.Equals(other.AboutGuestNotes)
) &&
(
this.Language == other.Language ||
this.Language != null &&
this.Language.Equals(other.Language)
) &&
(
this.HighChair == other.HighChair ||
this.HighChair != null &&
this.HighChair.Equals(other.HighChair)
) &&
(
this.Stroller == other.Stroller ||
this.Stroller != null &&
this.Stroller.Equals(other.Stroller)
) &&
(
this.Party == other.Party ||
this.Party != null &&
this.Party.Equals(other.Party)
) &&
(
this.Booth == other.Booth ||
this.Booth != null &&
this.Booth.Equals(other.Booth)
) &&
(
this.HighTop == other.HighTop ||
this.HighTop != null &&
this.HighTop.Equals(other.HighTop)
) &&
(
this.Table == other.Table ||
this.Table != null &&
this.Table.Equals(other.Table)
) &&
(
this.DepositToken == other.DepositToken ||
this.DepositToken != null &&
this.DepositToken.Equals(other.DepositToken)
) &&
(
this.PartyTypes == other.PartyTypes ||
this.PartyTypes != null &&
this.PartyTypes.SequenceEqual(other.PartyTypes)
) &&
(
this.CustomerProfile == other.CustomerProfile ||
this.CustomerProfile != null &&
this.CustomerProfile.Equals(other.CustomerProfile)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ReservationTime != null)
hash = hash * 59 + this.ReservationTime.GetHashCode();
if (this.GroupSize != null)
hash = hash * 59 + this.GroupSize.GetHashCode();
if (this.RestaurantId != null)
hash = hash * 59 + this.RestaurantId.GetHashCode();
if (this.CustomerName != null)
hash = hash * 59 + this.CustomerName.GetHashCode();
if (this.PhoneNumber != null)
hash = hash * 59 + this.PhoneNumber.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.Areas != null)
hash = hash * 59 + this.Areas.GetHashCode();
if (this.SpecialRequests != null)
hash = hash * 59 + this.SpecialRequests.GetHashCode();
if (this.AboutGuestNotes != null)
hash = hash * 59 + this.AboutGuestNotes.GetHashCode();
if (this.Language != null)
hash = hash * 59 + this.Language.GetHashCode();
if (this.HighChair != null)
hash = hash * 59 + this.HighChair.GetHashCode();
if (this.Stroller != null)
hash = hash * 59 + this.Stroller.GetHashCode();
if (this.Party != null)
hash = hash * 59 + this.Party.GetHashCode();
if (this.Booth != null)
hash = hash * 59 + this.Booth.GetHashCode();
if (this.HighTop != null)
hash = hash * 59 + this.HighTop.GetHashCode();
if (this.Table != null)
hash = hash * 59 + this.Table.GetHashCode();
if (this.DepositToken != null)
hash = hash * 59 + this.DepositToken.GetHashCode();
if (this.PartyTypes != null)
hash = hash * 59 + this.PartyTypes.GetHashCode();
if (this.CustomerProfile != null)
hash = hash * 59 + this.CustomerProfile.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// GroupSize (int?) maximum
if(this.GroupSize > (int?)999.0)
{
yield return new ValidationResult("Invalid value for GroupSize, must be a value less than or equal to 999.0.", new [] { "GroupSize" });
}
// GroupSize (int?) minimum
if(this.GroupSize < (int?)0.0)
{
yield return new ValidationResult("Invalid value for GroupSize, must be a value greater than or equal to 0.0.", new [] { "GroupSize" });
}
yield break;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.Serialization;
namespace XenAPI
{
public partial class HTTP
{
[Serializable]
public class TooManyRedirectsException : Exception
{
private readonly int redirect;
private readonly Uri uri;
public TooManyRedirectsException(int redirect, Uri uri)
{
this.redirect = redirect;
this.uri = uri;
}
public TooManyRedirectsException() : base() { }
public TooManyRedirectsException(string message) : base(message) { }
public TooManyRedirectsException(string message, Exception exception) : base(message, exception) { }
protected TooManyRedirectsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
redirect = info.GetInt32("redirect");
uri = (Uri)info.GetValue("uri", typeof(Uri));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("redirect", redirect);
info.AddValue("uri", uri, typeof(Uri));
base.GetObjectData(info, context);
}
}
[Serializable]
public class BadServerResponseException : Exception
{
public BadServerResponseException() : base() { }
public BadServerResponseException(string message) : base(message) { }
public BadServerResponseException(string message, Exception exception) : base(message, exception) { }
protected BadServerResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class CancelledException : Exception
{
public CancelledException() : base() { }
public CancelledException(string message) : base(message) { }
public CancelledException(string message, Exception exception) : base(message, exception) { }
protected CancelledException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public delegate bool FuncBool();
public delegate void UpdateProgressDelegate(int percent);
public delegate void DataCopiedDelegate(long bytes);
// Size of byte buffer used for GETs and PUTs
// (not the socket rx buffer)
public const int BUFFER_SIZE = 32 * 1024;
public const int MAX_REDIRECTS = 10;
public const int DEFAULT_HTTPS_PORT = 443;
#region Helper functions
private static void WriteLine(String txt, Stream stream)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", txt));
stream.Write(bytes, 0, bytes.Length);
}
private static void WriteLine(Stream stream)
{
WriteLine("", stream);
}
private static string ReadLine(Stream stream)
{
System.Text.StringBuilder result = new StringBuilder();
while (true)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
char c = Convert.ToChar(b);
result.Append(c);
if (c == '\n')
return result.ToString();
}
}
/// <summary>
/// Read HTTP headers, doing any redirects as necessary
/// </summary>
/// <param name="stream"></param>
/// <returns>True if a redirect has occurred - headers will need to be resent.</returns>
private static bool ReadHttpHeaders(ref Stream stream, IWebProxy proxy, bool nodelay, int timeout_ms)
{
string response = ReadLine(stream);
int code = getResultCode(response);
switch (code)
{
case 200:
break;
case 302:
string url = "";
while (true)
{
response = ReadLine(stream);
if (response.StartsWith("Location: "))
url = response.Substring(10);
if (response.Equals("\r\n") || response.Equals("\n") || response.Equals(""))
break;
}
Uri redirect = new Uri(url.Trim());
stream.Close();
stream = ConnectStream(redirect, proxy, nodelay, timeout_ms);
return true; // headers need to be sent again
default:
if (response.EndsWith("\r\n"))
response = response.Substring(0, response.Length - 2);
else if (response.EndsWith("\n"))
response = response.Substring(0, response.Length - 1);
stream.Close();
throw new BadServerResponseException(string.Format("Received error code {0} from the server", response));
}
while (true)
{
string line = ReadLine(stream);
if (System.Text.RegularExpressions.Regex.Match(line, "^\\s*$").Success)
break;
}
return false;
}
public static int getResultCode(string line)
{
string[] bits = line.Split(new char[] { ' ' });
return (bits.Length < 2 ? 0 : Int32.Parse(bits[1]));
}
public static bool UseSSL(Uri uri)
{
return uri.Scheme == "https" || uri.Port == DEFAULT_HTTPS_PORT;
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static long CopyStream(Stream inStream, Stream outStream,
DataCopiedDelegate progressDelegate, FuncBool cancellingDelegate)
{
long bytesWritten = 0;
byte[] buffer = new byte[BUFFER_SIZE];
DateTime lastUpdate = DateTime.Now;
while (cancellingDelegate == null || !cancellingDelegate())
{
int bytesRead = inStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
outStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
if (progressDelegate != null &&
DateTime.Now - lastUpdate > TimeSpan.FromMilliseconds(500))
{
progressDelegate(bytesWritten);
lastUpdate = DateTime.Now;
}
}
if (cancellingDelegate != null && cancellingDelegate())
throw new CancelledException();
if (progressDelegate != null)
progressDelegate(bytesWritten);
return bytesWritten;
}
/// <summary>
/// Build a URI from a hostname, a path, and some query arguments
/// </summary>
/// <param name="args">An even-length array, alternating argument names and values</param>
/// <returns></returns>
public static Uri BuildUri(string hostname, string path, params object[] args)
{
// The last argument may be an object[] in its own right, in which case we need
// to flatten the array.
List<object> flatargs = new List<object>();
foreach (object arg in args)
{
if (arg is IEnumerable<object>)
flatargs.AddRange((IEnumerable<object>)arg);
else
flatargs.Add(arg);
}
UriBuilder uri = new UriBuilder();
uri.Scheme = "https";
uri.Port = DEFAULT_HTTPS_PORT;
uri.Host = hostname;
uri.Path = path;
StringBuilder query = new StringBuilder();
for (int i = 0; i < flatargs.Count - 1; i += 2)
{
string kv;
// If the argument is null, don't include it in the URL
if (flatargs[i + 1] == null)
continue;
// bools are special because some xapi calls use presence/absence and some
// use "b=true" (not "True") and "b=false". But all accept "b=true" or absent.
if (flatargs[i + 1] is bool)
{
if (!((bool)flatargs[i + 1]))
continue;
kv = flatargs[i] + "=true";
}
else
kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString());
if (query.Length != 0)
query.Append('&');
query.Append(kv);
}
uri.Query = query.ToString();
return uri.Uri;
}
#endregion
private static NetworkStream ConnectSocket(Uri uri, bool nodelay, int timeout_ms)
{
AddressFamily addressFamily = uri.HostNameType == UriHostNameType.IPv6
? AddressFamily.InterNetworkV6
: AddressFamily.InterNetwork;
Socket socket =
new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = nodelay;
//socket.ReceiveBufferSize = 64 * 1024;
socket.ReceiveTimeout = timeout_ms;
socket.SendTimeout = timeout_ms;
socket.Connect(uri.Host, uri.Port);
return new NetworkStream(socket, true);
}
/// <summary>
/// This function will connect a stream to a uri (host and port),
/// negotiating proxies and SSL
/// </summary>
/// <param name="uri"></param>
/// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param>
/// <returns></returns>
public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms)
{
IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null;
if (mockProxy != null)
return mockProxy.GetStream(uri);
Stream stream;
bool useProxy = proxy != null && !proxy.IsBypassed(uri);
if (useProxy)
{
Uri proxyURI = proxy.GetProxy(uri);
stream = ConnectSocket(proxyURI, nodelay, timeout_ms);
}
else
{
stream = ConnectSocket(uri, nodelay, timeout_ms);
}
try
{
if (useProxy)
{
string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port);
WriteLine(line, stream);
WriteLine(stream);
ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms);
}
if (UseSSL(uri))
{
SslStream sslStream = new SslStream(stream, false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient("");
stream = sslStream;
}
return stream;
}
catch
{
stream.Close();
throw;
}
}
private static Stream DO_HTTP(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, params string[] headers)
{
Stream stream = ConnectStream(uri, proxy, nodelay, timeout_ms);
int redirects = 0;
do
{
if (redirects > MAX_REDIRECTS)
throw new TooManyRedirectsException(redirects, uri);
redirects++;
foreach (string header in headers)
WriteLine(header, stream);
WriteLine(stream);
stream.Flush();
}
while (ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms));
return stream;
}
//
// The following functions do all the HTTP headers related stuff
// returning the stream ready for use
//
public static Stream CONNECT(Uri uri, IWebProxy proxy, String session, int timeout_ms)
{
return DO_HTTP(uri, proxy, true, timeout_ms,
string.Format("CONNECT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host),
string.Format("Cookie: session_id={0}", session));
}
public static Stream PUT(Uri uri, IWebProxy proxy, long ContentLength, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("PUT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host),
string.Format("Content-Length: {0}", ContentLength));
}
public static Stream GET(Uri uri, IWebProxy proxy, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("GET {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host));
}
/// <summary>
/// A general HTTP PUT method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to PUT to</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to put</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Put(UpdateProgressDelegate progressDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read),
requestStream = PUT(uri, proxy, fileStream.Length, timeout_ms))
{
long len = fileStream.Length;
DataCopiedDelegate dataCopiedDelegate = delegate(long bytes)
{
if (progressDelegate != null && len > 0)
progressDelegate((int)((bytes * 100) / len));
};
CopyStream(fileStream, requestStream, dataCopiedDelegate, cancellingDelegate);
}
}
/// <summary>
/// A general HTTP GET method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="dataRxDelegate">Delegate called periodically (500 ms) with the number of bytes transferred</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to GET from</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to receive the data</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Get(DataCopiedDelegate dataCopiedDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
string tmpFile = Path.GetTempFileName();
try
{
using (Stream fileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.Write, FileShare.None),
downloadStream = GET(uri, proxy, timeout_ms))
{
CopyStream(downloadStream, fileStream, dataCopiedDelegate, cancellingDelegate);
fileStream.Flush();
}
File.Delete(path);
File.Move(tmpFile, path);
}
finally
{
File.Delete(tmpFile);
}
}
}
}
| |
using MatterHackers.Agg.Font;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes slider_ctrl_impl, slider_ctrl
//
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg.UI
{
public enum Orientation { Horizontal, Vertical };
public enum TickPlacement { None, BottomLeft, TopRight, Both };
public class SlideView
{
private Slider sliderAttachedTo;
public Color BackgroundColor { get; set; }
public Color TrackColor { get; set; }
public double TrackHeight { get; set; }
public TickPlacement TextPlacement { get; set; }
public Color TextColor { get; set; }
public StyledTypeFace TextStyle { get; set; }
public Color ThumbColor { get; set; }
public TickPlacement TickPlacement { get; set; }
public Color TickColor { get; set; }
public SlideView(Slider sliderWidget)
{
sliderAttachedTo = sliderWidget;
TrackHeight = 3 * GuiWidget.DeviceScale;
TextColor = Color.Black;
TrackColor = new Color(220, 220, 220);
ThumbColor = DefaultViewFactory.DefaultBlue;
sliderWidget.ValueChanged += new EventHandler(sliderWidget_ValueChanged);
sliderWidget.TextChanged += new EventHandler(sliderWidget_TextChanged);
SetFormatStringForText();
}
private void SetFormatStringForText()
{
if (sliderAttachedTo.Text != "")
{
string stringWithValue = string.Format(sliderAttachedTo.Text, sliderAttachedTo.Value);
sliderAttachedTo.sliderTextWidget.Text = stringWithValue;
Vector2 textPosition = GetTextPosition();
sliderAttachedTo.sliderTextWidget.OriginRelativeParent = textPosition;
}
}
private void sliderWidget_TextChanged(object sender, EventArgs e)
{
SetFormatStringForText();
}
private void sliderWidget_ValueChanged(object sender, EventArgs e)
{
SetFormatStringForText();
}
private RectangleDouble GetTrackBounds()
{
RectangleDouble trackBounds;
if (sliderAttachedTo.Orientation == Orientation.Horizontal)
{
trackBounds = new RectangleDouble(0, -TrackHeight / 2, sliderAttachedTo.TotalWidthInPixels, TrackHeight / 2);
}
else
{
trackBounds = new RectangleDouble(-TrackHeight / 2, 0, TrackHeight / 2, sliderAttachedTo.TotalWidthInPixels);
}
return trackBounds;
}
private RectangleDouble GetThumbBounds()
{
RectangleDouble thumbBounds = sliderAttachedTo.GetThumbHitBounds();
return thumbBounds;
}
private Vector2 GetTextPosition()
{
Vector2 textPosition;
if (sliderAttachedTo.Orientation == Orientation.Horizontal)
{
double textHeight = 0;
if (sliderAttachedTo.sliderTextWidget.Text != "")
{
textHeight = sliderAttachedTo.sliderTextWidget.Printer.TypeFaceStyle.EmSizeInPixels;
}
textPosition = new Vector2(sliderAttachedTo.TotalWidthInPixels / 2, GetThumbBounds().Bottom - textHeight);
}
else
{
textPosition = new Vector2(0, -24);
}
return textPosition;
}
public RectangleDouble GetTotalBounds()
{
RectangleDouble totalBounds = GetTrackBounds();
totalBounds.ExpandToInclude(GetThumbBounds());
if (sliderAttachedTo.sliderTextWidget.Text != "")
{
totalBounds.ExpandToInclude(sliderAttachedTo.sliderTextWidget.BoundsRelativeToParent);
}
return totalBounds;
}
public void DoDrawBeforeChildren(Graphics2D graphics2D)
{
// erase to the background color
graphics2D.FillRectangle(GetTotalBounds(), BackgroundColor);
}
public void DoDrawAfterChildren(Graphics2D graphics2D)
{
var track = new RoundedRect(GetTrackBounds(), TrackHeight / 2);
// draw the track
graphics2D.Render(track, TrackColor);
// now do the thumb
RectangleDouble thumbBounds = sliderAttachedTo.GetThumbHitBounds();
var thumbOutside = new RoundedRect(thumbBounds, sliderAttachedTo.ThumbWidth / 2);
graphics2D.Render(thumbOutside, ColorF.GetTweenColor(ThumbColor.ToColorF(), ColorF.Black.ToColorF(), .2).ToColor());
thumbBounds.Inflate(-1);
var thumbInside = new RoundedRect(thumbBounds, sliderAttachedTo.ThumbWidth / 2);
graphics2D.Render(thumbInside, ThumbColor);
}
}
public class Slider : GuiWidget
{
internal TextWidget sliderTextWidget; // this will print the 'Text' object for this widget.
public event EventHandler ValueChanged;
public event EventHandler SliderReleased;
public event EventHandler SliderGrabed;
public SlideView View { get; set; }
private double mouseDownOffsetFromThumbCenter;
private bool downOnThumb = false;
private double position0To1;
private double thumbHeight;
private int numTicks = 0;
public double Position0To1
{
get
{
return position0To1;
}
set
{
position0To1 = Math.Max(0, Math.Min(value, 1));
}
}
public double Value
{
get
{
return Minimum + (Maximum - Minimum) * Position0To1;
}
set
{
double newPosition0To1 = Math.Max(0, Math.Min((value - Minimum) / (Maximum - Minimum), 1));
if (newPosition0To1 != Position0To1)
{
Position0To1 = newPosition0To1;
if (ValueChanged != null)
{
ValueChanged(this, null);
}
Invalidate();
}
}
}
public override string Text
{
get
{
return base.Text;
}
set
{
sliderTextWidget.Text = value;
base.Text = value;
}
}
public double PositionPixelsFromFirstValue
{
get
{
return ThumbWidth / 2 + TrackWidth * Position0To1;
}
set
{
Position0To1 = (value - ThumbWidth / 2) / TrackWidth;
}
}
public Orientation Orientation { get; set; }
public double ThumbWidth { get; set; }
public double ThumbHeight
{
get
{
return Math.Max(thumbHeight, ThumbWidth);
}
set
{
thumbHeight = value;
}
}
public double TotalWidthInPixels { get; set; }
public double TrackWidth
{
get
{
return TotalWidthInPixels - ThumbWidth;
}
}
/// <summary>
/// There will always be 0 or at least two ticks, one at the start and one at the end.
/// </summary>
public int NumTicks
{
get
{
return numTicks;
}
set
{
numTicks = value;
if (numTicks == 1)
{
numTicks = 2;
}
}
}
public bool SnapToTicks { get; set; }
public double Minimum { get; set; }
public double Maximum { get; set; }
public bool SmallChange { get; set; }
public bool LargeChange { get; set; }
public Slider(Vector2 positionOfTrackFirstValue, double widthInPixels, double minimum = 0, double maximum = 1, Orientation orientation = UI.Orientation.Horizontal)
{
sliderTextWidget = new TextWidget("", 0, 0, justification: Justification.Center);
sliderTextWidget.AutoExpandBoundsToText = true;
AddChild(sliderTextWidget);
View = new SlideView(this);
OriginRelativeParent = positionOfTrackFirstValue;
TotalWidthInPixels = widthInPixels;
Orientation = orientation;
Minimum = minimum;
Maximum = maximum;
ThumbWidth = 10;
ThumbHeight = 20;
MinimumSize = new Vector2(Width, Height);
}
public Slider(Vector2 lowerLeft, Vector2 upperRight)
: this(new Vector2(lowerLeft.X, lowerLeft.Y + (upperRight.Y - lowerLeft.Y) / 2), upperRight.X - lowerLeft.X)
{
}
public Slider(double lowerLeftX, double lowerLeftY, double upperRightX, double upperRightY)
: this(new Vector2(lowerLeftX, lowerLeftY + (upperRightY - lowerLeftY) / 2), upperRightX - lowerLeftX)
{
}
public override RectangleDouble LocalBounds
{
get
{
return View.GetTotalBounds();
}
set
{
//OriginRelativeParent = new Vector2(value.Left, value.Bottom - View.GetTotalBounds().Bottom);
//throw new Exception("Figure out what this should do.");
}
}
public void SetRange(double minimum, double maximum)
{
Minimum = minimum;
Maximum = maximum;
}
public override void OnDraw(Graphics2D graphics2D)
{
View.DoDrawBeforeChildren(graphics2D);
base.OnDraw(graphics2D);
View.DoDrawAfterChildren(graphics2D);
}
public RectangleDouble GetThumbHitBounds()
{
if (Orientation == Orientation.Horizontal)
{
return new RectangleDouble(-ThumbWidth / 2 + PositionPixelsFromFirstValue, -ThumbHeight / 2,
ThumbWidth / 2 + PositionPixelsFromFirstValue, ThumbHeight / 2);
}
else
{
return new RectangleDouble(-ThumbHeight / 2, -ThumbWidth / 2 + PositionPixelsFromFirstValue,
ThumbHeight / 2, ThumbWidth / 2 + PositionPixelsFromFirstValue);
}
}
public double GetPosition0To1FromValue(double value)
{
return (value - Minimum) / (Maximum - Minimum);
}
public double GetPositionPixelsFromValue(double value)
{
return ThumbWidth / 2 + TrackWidth * GetPosition0To1FromValue(value);
}
public RectangleDouble GetTrackHitBounds()
{
if (Orientation == Orientation.Horizontal)
{
return new RectangleDouble(0, -ThumbHeight / 2,
TotalWidthInPixels, ThumbHeight / 2);
}
else
{
return new RectangleDouble(-ThumbHeight / 2, 0, ThumbHeight / 2, TotalWidthInPixels);
}
}
private double valueOnMouseDown;
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
valueOnMouseDown = Value;
double oldValue = Value;
Vector2 mousePos = mouseEvent.Position;
RectangleDouble thumbBounds = GetThumbHitBounds();
if (thumbBounds.Contains(mousePos))
{
if (Orientation == Orientation.Horizontal)
{
mouseDownOffsetFromThumbCenter = mousePos.X - PositionPixelsFromFirstValue;
}
else
{
mouseDownOffsetFromThumbCenter = mousePos.Y - PositionPixelsFromFirstValue;
}
downOnThumb = true;
SliderGrabed?.Invoke(this, mouseEvent);
}
else // let's check if we are on the track
{
RectangleDouble trackHitBounds = GetTrackHitBounds();
if (trackHitBounds.Contains(mousePos))
{
if (Orientation == Orientation.Horizontal)
{
PositionPixelsFromFirstValue = mousePos.X;
}
else
{
PositionPixelsFromFirstValue = mousePos.Y;
}
}
}
if (oldValue != Value)
{
if (ValueChanged != null)
{
ValueChanged(this, mouseEvent);
}
Invalidate();
}
base.OnMouseDown(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
Vector2 mousePos = mouseEvent.Position;
if (downOnThumb)
{
double oldValue = Value;
if (Orientation == Orientation.Horizontal)
{
PositionPixelsFromFirstValue = mousePos.X - mouseDownOffsetFromThumbCenter;
}
else
{
PositionPixelsFromFirstValue = mousePos.Y - mouseDownOffsetFromThumbCenter;
}
if (oldValue != Value)
{
if (ValueChanged != null)
{
ValueChanged(this, mouseEvent);
}
Invalidate();
}
}
base.OnMouseMove(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
downOnThumb = false;
base.OnMouseUp(mouseEvent);
SliderReleased?.Invoke(this, mouseEvent);
}
}
}
| |
/*
* 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 NPOI.SS.UserModel;
using NUnit.Framework;
using TestCases.SS.Formula.Functions;
using NPOI.OpenXml4Net.OPC;
using System.IO;
using TestCases.HSSF;
using NPOI.Util;
using NPOI.SS.Util;
namespace NPOI.XSSF.UserModel{
/**
* Performs much the same role as {@link TestFormulasFromSpreadsheet},
* except for a XSSF spreadsheet, not a HSSF one.
* This allows us to check that all our Formula Evaluation code
* is able to work for XSSF, as well as for HSSF.
*
* Periodically, you should open FormulaEvalTestData.xls in
* Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx
*
*/
[TestFixture]
public class TestFormulaEvaluatorOnXSSF
{
private class Result
{
public const int SOME_EVALUATIONS_FAILED = -1;
public const int ALL_EVALUATIONS_SUCCEEDED = +1;
public const int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/**
* Name of the Test spreadsheet (found in the standard Test data folder)
*/
public static String FILENAME = "FormulaEvalTestData_Copy.xlsx";
/**
* Row (zero-based) in the Test spreadsheet where the operator examples start.
*/
public static int START_OPERATORS_ROW_INDEX = 22; // Row '23'
/**
* Row (zero-based) in the Test spreadsheet where the function examples start.
*/
public static int START_FUNCTIONS_ROW_INDEX = 95; // Row '96'
/**
* Index of the column that Contains the function names
*/
public static int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B'
/**
* Used to indicate when there are no more functions left
*/
public static String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>";
/**
* Index of the column where the Test values start (for each function)
*/
public static short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D'
/**
* Each function takes 4 rows in the Test spreadsheet
*/
public static int NUMBER_OF_ROWS_PER_FUNCTION = 4;
}
private XSSFWorkbook workbook;
private ISheet sheet;
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionFailedError is thrown at the end
private int _functionFailureCount;
private int _functionSuccessCount;
private int _EvaluationFailureCount;
private int _EvaluationSuccessCount;
private static ICell GetExpectedValueCell(IRow row, short columnIndex)
{
if (row == null)
{
return null;
}
return row.GetCell(columnIndex);
}
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
switch (expected.CellType)
{
case CellType.Blank:
Assert.AreEqual(CellType.Blank, actual.CellType, msg);
break;
case CellType.Boolean:
Assert.AreEqual(CellType.Boolean, actual.CellType, msg);
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Error:
Assert.AreEqual(CellType.Error, actual.CellType, msg);
//if (false)
//{ // TODO: fix ~45 functions which are currently returning incorrect error values
// Assert.AreEqual(expected.ErrorCellValue, actual.ErrorValue, msg);
//}
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(CellType.Numeric, actual.CellType, msg);
AbstractNumericTestCase.AssertEquals(msg, expected.NumericCellValue, actual.NumberValue, TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR);
// double delta = Math.abs(expected.NumericCellValue-actual.NumberValue);
// double pctExpected = Math.abs(0.00001*expected.NumericCellValue);
// Assert.IsTrue(msg, delta <= pctExpected);
break;
case CellType.String:
Assert.AreEqual(CellType.String, actual.CellType, msg);
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
[SetUp]
public void SetUp()
{
if (workbook == null)
{
Stream is1 = HSSFTestDataSamples.OpenSampleFileStream(SS.FILENAME);
OPCPackage pkg = OPCPackage.Open(is1);
workbook = new XSSFWorkbook(pkg);
sheet = workbook.GetSheetAt(0);
}
_functionFailureCount = 0;
_functionSuccessCount = 0;
_EvaluationFailureCount = 0;
_EvaluationSuccessCount = 0;
}
/**
* Checks that we can actually open the file
*/
[Test]
public void TestOpen()
{
Assert.IsNotNull(workbook);
}
/**
* Disabled for now, as many things seem to break
* for XSSF, which is a shame
*/
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
NumberToTextConverter.RawDoubleBitsToText(BitConverter.DoubleToInt64Bits(1.0));
ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null);
ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null);
// example for debugging individual functions/operators:
// ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval");
// ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE");
// confirm results
String successMsg = "There were "
+ _EvaluationSuccessCount + " successful Evaluation(s) and "
+ _functionSuccessCount + " function(s) without error";
if (_functionFailureCount > 0)
{
String msg = _functionFailureCount + " function(s) failed in "
+ _EvaluationFailureCount + " Evaluation(s). " + successMsg;
throw new AssertionException(msg);
}
//if (false)
//{ // normally no output for successful Tests
// Console.WriteLine(this.GetType().Name + ": " + successMsg);
//}
}
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
* @param TestFocusFunctionName name of a single function/operator to Test alone.
* Typically pass <code>null</code> to Test all functions
*/
private void ProcessFunctionGroup(int startRowIndex, String testFocusFunctionName)
{
IFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
int rowIndex = startRowIndex;
while (true)
{
IRow r = sheet.GetRow(rowIndex);
String targetFunctionName = GetTargetFunctionName(r);
if (targetFunctionName == null)
{
throw new AssertionException("Test spreadsheet cell empty on row ("
+ (rowIndex + 1) + "). Expected function name or '"
+ SS.FUNCTION_NAMES_END_SENTINEL + "'");
}
if (targetFunctionName.Equals(SS.FUNCTION_NAMES_END_SENTINEL))
{
// found end of functions list
break;
}
if (testFocusFunctionName == null || targetFunctionName.Equals(testFocusFunctionName, StringComparison.OrdinalIgnoreCase))
{
// expected results are on the row below
IRow expectedValuesRow = sheet.GetRow(rowIndex + 1);
if (expectedValuesRow == null)
{
int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row
throw new AssertionException("Missing expected values row for function '"
+ targetFunctionName + " (row " + missingRowNum + ")");
}
switch (ProcessFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow))
{
case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break;
case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break;
case Result.NO_EVALUATIONS_FOUND: // do nothing
break;
default:
throw new RuntimeException("unexpected result");
}
}
rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION;
}
}
/**
*
* @return a constant from the local Result class denoting whether there were any Evaluation
* cases, and whether they all succeeded.
*/
private int ProcessFunctionRow(IFormulaEvaluator Evaluator, String targetFunctionName,
IRow formulasRow, IRow expectedValuesRow)
{
int result = Result.NO_EVALUATIONS_FOUND; // so far
short endcolnum = formulasRow.LastCellNum;
// iterate across the row for all the Evaluation cases
for (short colnum = SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++)
{
ICell c = formulasRow.GetCell(colnum);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
if (IsIgnoredFormulaTestCase(c.CellFormula))
{
continue;
}
CellValue actualValue;
try
{
actualValue = Evaluator.Evaluate(c);
}
catch (RuntimeException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
continue;
}
ICell expectedValueCell = GetExpectedValueCell(expectedValuesRow, colnum);
try
{
ConfirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.CellFormula + " @ " + formulasRow.RowNum + ":" + colnum,
expectedValueCell, actualValue);
_EvaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (AssertionException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
return result;
}
/*
* TODO - these are all formulas which currently (Apr-2008) break on ooxml
*/
private static bool IsIgnoredFormulaTestCase(String cellFormula)
{
if ("COLUMN(1:2)".Equals(cellFormula) || "ROW(2:3)".Equals(cellFormula))
{
// full row ranges are not Parsed properly yet.
// These cases currently work in svn tRunk because of another bug which causes the
// formula to Get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3)
return true;
}
if ("ISREF(currentcell())".Equals(cellFormula))
{
// currently throws NPE because unknown function "currentcell" causes name lookup
// Name lookup requires some equivalent object of the Workbook within xSSFWorkbook.
return true;
}
return false;
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void PrintshortStackTrace(TextWriter ps, Exception e)
{
//StackTraceElement[] stes = e.GetStackTrace();
//int startIx = 0;
//// Skip any top frames inside junit.framework.Assert
//while(startIx<stes.Length) {
// if(!stes[startIx].GetClassName().Equals(Assert.class.GetName())) {
// break;
// }
// startIx++;
//}
//// Skip bottom frames (part of junit framework)
//int endIx = startIx+1;
//while(endIx < stes.Length) {
// if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) {
// break;
// }
// endIx++;
//}
//if(startIx >= endIx) {
// // something went wrong. just print the whole stack trace
// e.printStackTrace(ps);
//}
//endIx -= 4; // Skip 4 frames of reflection invocation
//ps.println(e.ToString());
//for(int i=startIx; i<endIx; i++) {
// ps.println("\tat " + stes[i].ToString());
//}
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
private static String GetTargetFunctionName(IRow r)
{
if (r == null)
{
System.Console.WriteLine("Warning - given null row, can't figure out function name");
return null;
}
ICell cell = r.GetCell(SS.COLUMN_INDEX_FUNCTION_NAME);
if (cell == null)
{
System.Console.WriteLine("Warning - Row " + r.RowNum + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
return null;
}
if (cell.CellType == CellType.Blank)
{
return null;
}
if (cell.CellType == CellType.String)
{
return cell.RichStringCellValue.String;
}
throw new AssertionException("Bad cell type for 'function name' column: ("
+ cell.CellType + ") row (" + (r.RowNum + 1) + ")");
}
}
}
| |
//
// 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.Search;
using Microsoft.Azure.Search.Models;
namespace Microsoft.Azure.Search
{
/// <summary>
/// Client that can be used to manage and query indexes and documents on an
/// Azure Search service. (see
/// https://msdn.microsoft.com/library/azure/dn798935.aspx for more
/// information)
/// </summary>
public partial class SearchServiceClient : ServiceClient<SearchServiceClient>, ISearchServiceClient
{
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 SearchCredentials _credentials;
/// <summary>
/// Gets the credentials used to authenticate to an Azure Search
/// service. (see
/// https://msdn.microsoft.com/library/azure/dn798935.aspx for more
/// information)
/// </summary>
public SearchCredentials Credentials
{
get { return this._credentials; }
}
private IDataSourceOperations _dataSources;
/// <summary>
/// Operations for managing datasources. (see
/// https://msdn.microsoft.com/library/azure/dn946891.aspx for more
/// information)
/// </summary>
public virtual IDataSourceOperations DataSources
{
get { return this._dataSources; }
}
private IIndexerOperations _indexers;
/// <summary>
/// Operations for managing indexers. (see
/// https://msdn.microsoft.com/library/azure/dn946891.aspx for more
/// information)
/// </summary>
public virtual IIndexerOperations Indexers
{
get { return this._indexers; }
}
private IIndexOperations _indexes;
/// <summary>
/// Operations for managing indexes. (see
/// https://msdn.microsoft.com/library/azure/dn798918.aspx for more
/// information)
/// </summary>
public virtual IIndexOperations Indexes
{
get { return this._indexes; }
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
private SearchServiceClient()
: base()
{
this._dataSources = new DataSourceOperations(this);
this._indexers = new IndexerOperations(this);
this._indexes = new IndexOperations(this);
this._apiVersion = "2015-02-28";
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets the credentials used to authenticate to an Azure
/// Search service. (see
/// https://msdn.microsoft.com/library/azure/dn798935.aspx for more
/// information)
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SearchServiceClient(SearchCredentials 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 SearchServiceClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private SearchServiceClient(HttpClient httpClient)
: base(httpClient)
{
this._dataSources = new DataSourceOperations(this);
this._indexers = new IndexerOperations(this);
this._indexes = new IndexOperations(this);
this._apiVersion = "2015-02-28";
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets the credentials used to authenticate to an Azure
/// Search service. (see
/// https://msdn.microsoft.com/library/azure/dn798935.aspx for more
/// information)
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SearchServiceClient(SearchCredentials 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>
/// Clones properties from current instance to another
/// SearchServiceClient instance
/// </summary>
/// <param name='client'>
/// Instance of SearchServiceClient to clone to
/// </param>
protected override void Clone(ServiceClient<SearchServiceClient> client)
{
base.Clone(client);
if (client is SearchServiceClient)
{
SearchServiceClient clonedClient = ((SearchServiceClient)client);
clonedClient._credentials = this._credentials;
clonedClient._apiVersion = this._apiVersion;
clonedClient._baseUri = this._baseUri;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type IndexActionType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static IndexActionType ParseIndexActionType(string value)
{
if ("upload".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexActionType.Upload;
}
if ("merge".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexActionType.Merge;
}
if ("mergeOrUpload".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexActionType.MergeOrUpload;
}
if ("delete".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexActionType.Delete;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type IndexActionType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string IndexActionTypeToString(IndexActionType value)
{
if (value == IndexActionType.Upload)
{
return "upload";
}
if (value == IndexActionType.Merge)
{
return "merge";
}
if (value == IndexActionType.MergeOrUpload)
{
return "mergeOrUpload";
}
if (value == IndexActionType.Delete)
{
return "delete";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type IndexerExecutionStatus.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static IndexerExecutionStatus ParseIndexerExecutionStatus(string value)
{
if ("transientFailure".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerExecutionStatus.TransientFailure;
}
if ("success".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerExecutionStatus.Success;
}
if ("inProgress".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerExecutionStatus.InProgress;
}
if ("reset".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerExecutionStatus.Reset;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type IndexerExecutionStatus to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string IndexerExecutionStatusToString(IndexerExecutionStatus value)
{
if (value == IndexerExecutionStatus.TransientFailure)
{
return "transientFailure";
}
if (value == IndexerExecutionStatus.Success)
{
return "success";
}
if (value == IndexerExecutionStatus.InProgress)
{
return "inProgress";
}
if (value == IndexerExecutionStatus.Reset)
{
return "reset";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type IndexerStatus.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static IndexerStatus ParseIndexerStatus(string value)
{
if ("unknown".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerStatus.Unknown;
}
if ("error".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerStatus.Error;
}
if ("running".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return IndexerStatus.Running;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type IndexerStatus to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string IndexerStatusToString(IndexerStatus value)
{
if (value == IndexerStatus.Unknown)
{
return "unknown";
}
if (value == IndexerStatus.Error)
{
return "error";
}
if (value == IndexerStatus.Running)
{
return "running";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type ScoringFunctionAggregation.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static ScoringFunctionAggregation ParseScoringFunctionAggregation(string value)
{
if ("sum".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionAggregation.Sum;
}
if ("average".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionAggregation.Average;
}
if ("minimum".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionAggregation.Minimum;
}
if ("maximum".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionAggregation.Maximum;
}
if ("firstMatching".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionAggregation.FirstMatching;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type ScoringFunctionAggregation to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string ScoringFunctionAggregationToString(ScoringFunctionAggregation value)
{
if (value == ScoringFunctionAggregation.Sum)
{
return "sum";
}
if (value == ScoringFunctionAggregation.Average)
{
return "average";
}
if (value == ScoringFunctionAggregation.Minimum)
{
return "minimum";
}
if (value == ScoringFunctionAggregation.Maximum)
{
return "maximum";
}
if (value == ScoringFunctionAggregation.FirstMatching)
{
return "firstMatching";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type ScoringFunctionInterpolation.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static ScoringFunctionInterpolation ParseScoringFunctionInterpolation(string value)
{
if ("linear".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionInterpolation.Linear;
}
if ("constant".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionInterpolation.Constant;
}
if ("quadratic".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionInterpolation.Quadratic;
}
if ("logarithmic".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ScoringFunctionInterpolation.Logarithmic;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type ScoringFunctionInterpolation to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string ScoringFunctionInterpolationToString(ScoringFunctionInterpolation value)
{
if (value == ScoringFunctionInterpolation.Linear)
{
return "linear";
}
if (value == ScoringFunctionInterpolation.Constant)
{
return "constant";
}
if (value == ScoringFunctionInterpolation.Quadratic)
{
return "quadratic";
}
if (value == ScoringFunctionInterpolation.Logarithmic)
{
return "logarithmic";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type SearchMode.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static SearchMode ParseSearchMode(string value)
{
if ("any".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return SearchMode.Any;
}
if ("all".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return SearchMode.All;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type SearchMode to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string SearchModeToString(SearchMode value)
{
if (value == SearchMode.Any)
{
return "any";
}
if (value == SearchMode.All)
{
return "all";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type SuggesterSearchMode.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static SuggesterSearchMode ParseSuggesterSearchMode(string value)
{
if ("analyzingInfixMatching".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return SuggesterSearchMode.AnalyzingInfixMatching;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type SuggesterSearchMode to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string SuggesterSearchModeToString(SuggesterSearchMode value)
{
if (value == SuggesterSearchMode.AnalyzingInfixMatching)
{
return "analyzingInfixMatching";
}
throw new ArgumentOutOfRangeException("value");
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endianness" of the word processing!
*/
public class Sha1Digest
: GeneralDigest
{
private const int DigestLength = 20;
private uint H1, H2, H3, H4, H5;
private uint[] X = new uint[80];
private int xOff;
public Sha1Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha1Digest(Sha1Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(Sha1Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "SHA-1"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(H1, output, outOff);
Pack.UInt32_To_BE(H2, output, outOff + 4);
Pack.UInt32_To_BE(H3, output, outOff + 8);
Pack.UInt32_To_BE(H4, output, outOff + 12);
Pack.UInt32_To_BE(H5, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
Array.Clear(X, 0, X.Length);
}
//
// Additive constants
//
private const uint Y1 = 0x5a827999;
private const uint Y2 = 0x6ed9eba1;
private const uint Y3 = 0x8f1bbcdc;
private const uint Y4 = 0xca62c1d6;
private static uint F(uint u, uint v, uint w)
{
return (u & v) | (~u & w);
}
private static uint H(uint u, uint v, uint w)
{
return u ^ v ^ w;
}
private static uint G(uint u, uint v, uint w)
{
return (u & v) | (u & w) | (v & w);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = H1;
uint B = H2;
uint C = H3;
uint D = H4;
uint E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
//
// round 4
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
public override IMemoable Copy()
{
return new Sha1Digest(this);
}
public override void Reset(IMemoable other)
{
Sha1Digest d = (Sha1Digest)other;
CopyIn(d);
}
}
}
#endif
| |
#region Header
#pragma warning disable 1587 // XML comment is not placed on a valid language element
/**
* Lexer.cs
* JSON lexer implementation based on a finite state machine.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#pragma warning restore 1587 // XML comment is not placed on a valid language element
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Htc.Vita.Core.Json.LitJson
{
internal class FsmContext
{
public bool Return;
public int NextState;
public Lexer L;
public int StateStack;
}
internal class Lexer
{
#region Fields
private delegate bool StateHandler (FsmContext ctx);
private static readonly int[] fsm_return_table;
private static readonly StateHandler[] fsm_handler_table;
private bool allow_comments;
private bool allow_single_quoted_strings;
private bool end_of_input;
private FsmContext fsm_context;
private int input_buffer;
private int input_char;
private TextReader reader;
private int state;
private StringBuilder string_buffer;
private string string_value;
private int token;
private int unichar;
#endregion
#region Properties
public bool AllowComments {
get { return allow_comments; }
set { allow_comments = value; }
}
public bool AllowSingleQuotedStrings {
get { return allow_single_quoted_strings; }
set { allow_single_quoted_strings = value; }
}
public bool EndOfInput {
get { return end_of_input; }
}
public int Token {
get { return token; }
}
public string StringValue {
get { return string_value; }
}
#endregion
#region Constructors
static Lexer ()
{
PopulateFsmTables (out fsm_handler_table, out fsm_return_table);
}
public Lexer (TextReader reader)
{
allow_comments = true;
allow_single_quoted_strings = true;
input_buffer = 0;
string_buffer = new StringBuilder (128);
state = 1;
end_of_input = false;
this.reader = reader;
fsm_context = new FsmContext ();
fsm_context.L = this;
}
#endregion
#region Static Methods
private static int HexValue (int digit)
{
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables (out StateHandler[] fsm_handler_table, out int[] fsm_return_table)
{
// See section A.1. of the manual for details of the finite
// state machine.
fsm_handler_table = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
fsm_return_table = new int[28] {
(int) ParserToken.Char,
0,
(int) ParserToken.Number,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
0,
(int) ParserToken.True,
0,
0,
0,
(int) ParserToken.False,
0,
0,
(int) ParserToken.Null,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar (int esc_char)
{
switch (esc_char) {
case '"':
case '\'':
case '\\':
case '/':
return Convert.ToChar (esc_char);
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
default:
// Unreachable
return '?';
}
}
private static bool State1 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (! ctx.L.allow_single_quoted_strings)
return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (! ctx.L.allow_comments)
return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State20 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append (
ProcessEscChar (ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22 (FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' ||
ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' ||
ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue (ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append (
Convert.ToChar (ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State24 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '\'':
ctx.L.input_char = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*')
continue;
if (ctx.L.input_char == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
#endregion
private bool GetChar ()
{
if ((input_char = NextChar ()) != -1)
return true;
end_of_input = true;
return false;
}
private int NextChar ()
{
if (input_buffer != 0) {
int tmp = input_buffer;
input_buffer = 0;
return tmp;
}
return reader.Read ();
}
public bool NextToken ()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (! handler (fsm_context))
throw new JsonException (input_char);
if (end_of_input)
return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString ();
string_buffer.Remove (0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int) ParserToken.Char)
token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
private void UngetChar ()
{
input_buffer = input_char;
}
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
using JCSLA;
namespace QED.Business{
/// <summary>
/// Summary description for defects.
/// </summary>
public enum DefectStatus {
//TODO Get status codes
a, b
}
public class Defects : BusinessCollectionBase {
const string _table = "defects";
Effort _eff;
BusinessBase _parent;
#region Collection Members
public Defect Add(Defect def) {
def.BusinessCollection = this;
def.Parent = this._parent;
List.Add(def); return def;
}
public bool Contains(Defect def) {
foreach(Defect obj in List) {
if (obj.Equals(def)){
return true;
}
}
return false;
}
public Defect this[int id] {
get{
return (Defect) List[id];
}
}
public Defect item(int id) {
foreach(Defect obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
#endregion
#region DB Access and ctors
public Defects() {
}
public Defects(BusinessBase parent) {
Defect def;
string SQL;
_parent = parent;
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
using(MySqlCommand cmd = conn.CreateCommand()){
if (parent is Effort){
SQL = "SELECT * FROM " + _table + " WHERE effId = @effId and forRoll = 0";
cmd.Parameters.Add("@effId", parent.Id);
}else{
SQL = "SELECT * FROM " + _table + " WHERE rollId = @rollId and forRoll = 1";
cmd.Parameters.Add("@rollId", parent.Id);
}
cmd.CommandText = SQL;
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()) {
def = new Defect(dr);
def.BusinessCollection = this;
List.Add(def);
}
conn.Close();
}
}
}
}
public BusinessBase Parent{
get{
return _parent;
}
set{
_parent = value;
}
}
public void Update() {
foreach (Defect def in List) {
def.Update();
}
}
#endregion
#region Validation Management
#endregion
}
public class Defect : BusinessBase {
#region Instance Data
int _id = -1;
string _desc = "";
int _effId = -1;
int _rollId = -1;
DefectStatus _status;
const string _table = "defects";
MySqlDBLayer _dbLayer;
BusinessCollectionBase _businessCollection;
string _createdBy = "";
string _resolver = "";
Effort _effort;
Rollout _rollout;
BusinessBase _parent;
bool _forRoll = false;
#endregion
#region DB Access / ctors
public Defect() {
Setup();
base.MarkNew();
}
public Defect(string desc) {
Setup();
_desc = desc;
base.MarkNew();
}
public Defect(int id) {
Setup();
this.Load(id);
}
public override void SetId(int id) {
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public override string Table {
get {
return _table;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public Defect(MySqlDataReader dr) {
this.Load(dr);
}
public void Load(int id) {
SetId(id);
using(MySqlConnection conn = (MySqlConnection) this.Conn){
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + this.Table + " WHERE ID = @ID", conn);
cmd.Parameters.Add("@Id", this.Id);
using(MySqlDataReader dr = cmd.ExecuteReader()){
if (dr.HasRows) {
dr.Read();
this.Load(dr);
}else{
throw new Exception("Defect " + id + " doesn't exist.");
}
}
}
}
public void Load(MySqlDataReader dr) {
Setup();
SetId(Convert.ToInt32(dr["id"]));
this._desc = dr["desc_"].ToString();
this._effId = Convert.ToInt32(dr["effId"]);
this._rollId = Convert.ToInt32(dr["rollId"]);
this._resolver = dr["resolver"].ToString();
this._createdBy = dr["createdBy"].ToString();
//this._status = dr["Status"].ToString();
this._forRoll = Convert.ToBoolean(dr["forRoll"]);
MarkOld();
}
public override void Update(){
_dbLayer.Update();
}
public override object Conn {
get {
return Connections.Inst.item("QED_DB").MySqlConnection;
}
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@Desc_", this.Desc);
paramHash.Add("@RollId", this._rollId);
paramHash.Add("@EffId", this._effId);
paramHash.Add("@CreatedBy", this.CreatedBy);
paramHash.Add("@Resolver", this.Resolver);
paramHash.Add("@forRoll", this.ForRoll);
return paramHash;
}
}
#endregion
#region Business Properties
public override int Id {
get {
return _id;
}
}
public string Desc{
get{
return _desc;
}
set{
SetValue(ref _desc, value);
}
}
public DefectStatus Status {
get {
return DefectStatus.a;
}
}
public Effort Effort{
get{
if (_effort == null){
if (_effId != -1){
_effort = new Effort(_effId, false);
return _effort;
}else{
return null;
}
}else{
return _effort;
}
}
set{
_effort = (Effort) SetValue(value);
_effId = _effort.Id;
}
}
public Rollout Rollout{
get{
if (_rollout == null){
if (_rollId != -1){
_rollout = new Rollout(_rollId);
return _rollout;
}else{
return null;
}
}else{
return _rollout;
}
}
set{
_rollout = (Rollout) SetValue(value);
_rollId = _rollout.Id;
}
}
public string CreatedBy{
get{
return _createdBy;
}
set{
SetValue(ref _createdBy, value);
}
}
public string Resolver{
get{
return _resolver;
}
set{
SetValue(ref _resolver, value);
}
}
public BusinessBase Parent{
get{
return _parent;
}
set{
if (value is Effort) {
this.Effort = (Effort)value;
}else{
this.Rollout = (Rollout)value;
}
}
}
public bool ForRoll{
get{
return _forRoll;
}
set{
SetValue(ref _forRoll, value);
}
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
BrokenRules br = new BrokenRules();
br.Assert("NO_DESC", "Must provide a description", this.Desc == "");
br.Assert("NO_PARENT", "No parent specified", this._effId== -1 && this._rollId == -1);
br.Assert("NO_CREATOR", "No creator specified", this.CreatedBy == "");
return br;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Correspondence.Mementos;
using Correspondence.Strategy;
using Assisticant.Fields;
using Assisticant;
namespace Correspondence.Networking
{
internal class AsynchronousServerProxy
{
private enum ReceiveState
{
NotReceiving,
Receiving,
Invalidated
}
private const long ClientDatabaseId = 0;
private IAsynchronousCommunicationStrategy _communicationStrategy;
private int _peerId;
private ISubscriptionProvider _subscriptionProvider;
private Model _model;
private IStorageStrategy _storageStrategy;
private Observable<bool> _sending = new Observable<bool>();
private Observable<ReceiveState> _receiveState = new Observable<ReceiveState>();
private Observable<Exception> _lastException = new Observable<Exception>();
private List<PushSubscriptionProxy> _pushSubscriptions = new List<PushSubscriptionProxy>();
private Computed _depPushSubscriptions;
public AsynchronousServerProxy(
ISubscriptionProvider subscriptionProvider,
Model model,
IStorageStrategy storageStrategy,
IAsynchronousCommunicationStrategy communicationStrategy,
int peerId)
{
_subscriptionProvider = subscriptionProvider;
_model = model;
_storageStrategy = storageStrategy;
_communicationStrategy = communicationStrategy;
_peerId = peerId;
_depPushSubscriptions = new Computed(UpdatePushSubscriptions);
}
public IAsynchronousCommunicationStrategy CommunicationStrategy
{
get { return _communicationStrategy; }
}
public int PeerId
{
get { return _peerId; }
}
public bool Synchronizing
{
get
{
lock (this)
{
return
_receiveState.Value == ReceiveState.Receiving ||
_receiveState.Value == ReceiveState.Invalidated ||
_sending.Value == true;
}
}
}
public Exception LastException
{
get
{
lock (this)
{
return _lastException;
}
}
}
public void BeginSending()
{
lock (this)
{
if (_sending)
return;
}
Send();
}
private void Send()
{
lock (this)
{
TimestampID timestamp = _storageStrategy.LoadOutgoingTimestamp(_peerId);
List<UnpublishMemento> unpublishedMessages = new List<UnpublishMemento>();
FactTreeMemento messageBodies = _model.GetMessageBodies(ref timestamp, _peerId, unpublishedMessages);
bool anyMessages = messageBodies != null && messageBodies.Facts.Any();
if (anyMessages)
{
_communicationStrategy.BeginPost(messageBodies, _model.ClientDatabaseGuid, unpublishedMessages, delegate(bool succeeded)
{
if (succeeded)
{
_storageStrategy.SaveOutgoingTimestamp(_peerId, timestamp);
Send();
}
else
{
OnSendError(null);
}
}, OnSendError);
}
_sending.Value = anyMessages;
}
}
public void BeginReceiving()
{
if (ShouldReceive())
Receive();
}
private bool ShouldReceive()
{
lock (this)
{
if (_receiveState.Value == ReceiveState.NotReceiving)
{
_receiveState.Value = ReceiveState.Receiving;
return true;
}
else if (_receiveState.Value == ReceiveState.Receiving)
{
_receiveState.Value = ReceiveState.Invalidated;
return false;
}
else //if (_receiveState.Value == ReceiveState.Invalidated)
{
return false;
}
}
}
private void Receive()
{
lock (this)
{
FactTreeMemento pivotTree = new FactTreeMemento(ClientDatabaseId);
List<FactID> pivotIds = new List<FactID>();
_depPushSubscriptions.OnGet();
GetPivots(pivotTree, pivotIds, _peerId);
bool anyPivots = pivotIds.Any();
if (anyPivots)
{
List<PivotMemento> pivots = new List<PivotMemento>();
foreach (FactID pivotId in pivotIds)
{
TimestampID timestamp = _storageStrategy.LoadIncomingTimestamp(_peerId, pivotId);
pivots.Add(new PivotMemento(pivotId, timestamp));
}
_communicationStrategy.BeginGetMany(pivotTree, pivots, _model.ClientDatabaseGuid, delegate(FactTreeMemento messageBody, IEnumerable<PivotMemento> newTimestamps)
{
bool receivedFacts = messageBody.Facts.Any();
if (receivedFacts)
{
_model.ReceiveMessage(messageBody, _peerId);
foreach (PivotMemento pivot in newTimestamps)
{
_storageStrategy.SaveIncomingTimestamp(_peerId, pivot.PivotId, pivot.Timestamp);
}
}
if (receivedFacts || _communicationStrategy.IsLongPolling)
Receive();
else
{
if (EndReceiving())
Receive();
}
}, OnReceiveError);
}
if (_receiveState.Value == ReceiveState.Receiving && !anyPivots)
_receiveState.Value = ReceiveState.NotReceiving;
}
}
private bool EndReceiving()
{
lock (this)
{
if (_receiveState.Value == ReceiveState.Invalidated)
{
_receiveState.Value = ReceiveState.Receiving;
return true;
}
else
{
_receiveState.Value = ReceiveState.NotReceiving;
return false;
}
}
}
public void Notify(CorrespondenceFact pivot, string text1, string text2)
{
FactTreeMemento pivotTree = new FactTreeMemento(ClientDatabaseId);
_model.AddToFactTree(pivotTree, pivot.ID, _peerId);
_communicationStrategy.Notify(
pivotTree,
pivot.ID,
_model.ClientDatabaseGuid,
text1,
text2);
}
private void UpdatePushSubscriptions()
{
using (var bin = _pushSubscriptions.Recycle())
{
var pivots = _subscriptionProvider.Subscriptions
.SelectMany(subscription => subscription.Pivots)
.Where(pivot => pivot != null);
var pushSubscriptions =
from pivot in pivots
select bin.Extract(new PushSubscriptionProxy(_model, this, pivot));
_pushSubscriptions = pushSubscriptions.ToList();
foreach (PushSubscriptionProxy pushSubscription in _pushSubscriptions)
{
pushSubscription.Subscribe();
}
}
}
private void GetPivots(FactTreeMemento pivotTree, List<FactID> pivotIds, int peerId)
{
foreach (Subscription subscription in _subscriptionProvider.Subscriptions)
{
if (subscription.Pivots != null)
{
foreach (CorrespondenceFact pivot in subscription.Pivots)
{
if (pivot == null)
continue;
FactID pivotId = pivot.ID;
_model.AddToFactTree(pivotTree, pivotId, peerId);
pivotIds.Add(pivotId);
}
}
}
}
private void OnSendError(Exception exception)
{
lock (this)
{
_sending.Value = false;
_lastException.Value = exception;
}
}
private void OnReceiveError(Exception exception)
{
lock (this)
{
_receiveState.Value = ReceiveState.NotReceiving;
_lastException.Value = exception;
}
}
public void TriggerSubscriptionUpdate()
{
lock (this)
{
_depPushSubscriptions.OnGet();
}
}
public void AfterTriggerSubscriptionUpdate()
{
if (_communicationStrategy.IsLongPolling)
_communicationStrategy.Interrupt(_model.ClientDatabaseGuid);
BeginReceiving();
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// JoinQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// A join operator takes a left query tree and a right query tree, and then yields the
/// matching pairs between the two. LINQ supports equi-key-based joins. Hence, a key-
/// selection function for the left and right data types will yield keys of the same
/// type for both. We then merely have to match elements from the left with elements from
/// the right that have the same exact key. Note that this is an inner join. In other
/// words, outer elements with no matching inner elements do not appear in the output.
///
/// Hash-joins work in two phases:
///
/// (1) Building - we build a hash-table from one of the data sources. In the case
/// of this specific operator, the table is built from the hash-codes of
/// keys selected via the key selector function. Because elements may share
/// the same key, the table must support one-key-to-many-values.
/// (2) Probing - for each element in the data source not used for building, we
/// use its key to look into the hash-table. If we find elements under this
/// key, we just enumerate all of them, yielding them as join matches.
///
/// Because hash-tables exhibit on average O(1) lookup, we turn what would have been
/// an O(n*m) algorithm -- in the case of nested loops joins -- into an O(n) algorithm.
/// We of course require some additional storage to do so, but in general this pays.
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class JoinQueryOperator<TLeftInput, TRightInput, TKey, TOutput> : BinaryQueryOperator<TLeftInput, TRightInput, TOutput>
{
private readonly Func<TLeftInput, TKey> _leftKeySelector; // The key selection routine for the outer (left) data source.
private readonly Func<TRightInput, TKey> _rightKeySelector; // The key selection routine for the inner (right) data source.
private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // The result selection routine.
private readonly IEqualityComparer<TKey> _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Constructs a new join operator.
//
internal JoinQueryOperator(ParallelQuery<TLeftInput> left, ParallelQuery<TRightInput> right,
Func<TLeftInput, TKey> leftKeySelector,
Func<TRightInput, TKey> rightKeySelector,
Func<TLeftInput, TRightInput, TOutput> resultSelector,
IEqualityComparer<TKey> keyComparer)
: base(left, right)
{
Debug.Assert(left != null && right != null, "child data sources cannot be null");
Debug.Assert(leftKeySelector != null, "left key selector must not be null");
Debug.Assert(rightKeySelector != null, "right key selector must not be null");
Debug.Assert(resultSelector != null, "need a result selector function");
_leftKeySelector = leftKeySelector;
_rightKeySelector = rightKeySelector;
_resultSelector = resultSelector;
_keyComparer = keyComparer;
_outputOrdered = LeftChild.OutputOrdered;
SetOrdinalIndex(OrdinalIndexState.Shuffled);
}
public override void WrapPartitionedStream<TLeftKey, TRightKey>(
PartitionedStream<TLeftInput, TLeftKey> leftStream, PartitionedStream<TRightInput, TRightKey> rightStream,
IPartitionedStreamRecipient<TOutput> outputRecipient, bool preferStriping, QuerySettings settings)
{
Debug.Assert(rightStream.PartitionCount == leftStream.PartitionCount);
if (LeftChild.OutputOrdered)
{
if(ExchangeUtilities.IsWorseThan(LeftChild.OrdinalIndexState, OrdinalIndexState.Increasing))
{
PartitionedStream<TLeftInput, int> leftStreamInt =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, OutputOrdered, preferStriping, settings)
.GetPartitionedStream();
WrapPartitionedStreamHelper<int, TRightKey>(
ExchangeUtilities.HashRepartitionOrdered(leftStreamInt, _leftKeySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
rightStream, outputRecipient, settings.CancellationState.MergedCancellationToken);
}
else
{
WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
ExchangeUtilities.HashRepartitionOrdered(leftStream, _leftKeySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
rightStream, outputRecipient, settings.CancellationState.MergedCancellationToken);
}
}
else
{
WrapPartitionedStreamHelper<int, TRightKey>(
ExchangeUtilities.HashRepartition(leftStream, _leftKeySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
rightStream, outputRecipient, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TLeftKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
PartitionedStream<Pair<TLeftInput, TKey>, TLeftKey> leftHashStream, PartitionedStream<TRightInput, TRightKey> rightPartitionedStream,
IPartitionedStreamRecipient<TOutput> outputRecipient, CancellationToken cancellationToken)
{
if (RightChild.OutputOrdered && LeftChild.OutputOrdered)
{
PairOutputKeyBuilder<TLeftKey, TRightKey> outputKeyBuilder = new PairOutputKeyBuilder<TLeftKey, TRightKey>();
IComparer<Pair<TLeftKey, TRightKey>> outputKeyComparer =
new PairComparer<TLeftKey, TRightKey>(leftHashStream.KeyComparer, rightPartitionedStream.KeyComparer);
WrapPartitionedStreamHelper<TLeftKey, TRightKey, Pair<TLeftKey, TRightKey>>(leftHashStream,
ExchangeUtilities.HashRepartitionOrdered(rightPartitionedStream, _rightKeySelector, _keyComparer, null, cancellationToken),
outputKeyBuilder, outputKeyComparer, outputRecipient, cancellationToken);
}
else
{
LeftKeyOutputKeyBuilder<TLeftKey, int> outputKeyBuilder = new LeftKeyOutputKeyBuilder<TLeftKey, int>();
WrapPartitionedStreamHelper<TLeftKey, int, TLeftKey>(leftHashStream,
ExchangeUtilities.HashRepartition(rightPartitionedStream, _rightKeySelector, _keyComparer, null, cancellationToken),
outputKeyBuilder, leftHashStream.KeyComparer, outputRecipient, cancellationToken);
}
}
private void WrapPartitionedStreamHelper<TLeftKey, TRightKey, TOutputKey>(
PartitionedStream<Pair<TLeftInput, TKey>, TLeftKey> leftHashStream, PartitionedStream<Pair<TRightInput, TKey>, TRightKey> rightHashStream,
HashJoinOutputKeyBuilder<TLeftKey, TRightKey, TOutputKey> outputKeyBuilder, IComparer<TOutputKey> outputKeyComparer,
IPartitionedStreamRecipient<TOutput> outputRecipient, CancellationToken cancellationToken)
{
int partitionCount = leftHashStream.PartitionCount;
PartitionedStream<TOutput, TOutputKey> outputStream =
new PartitionedStream<TOutput, TOutputKey>(partitionCount, outputKeyComparer, OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
JoinHashLookupBuilder<TRightInput, TRightKey, TKey> rightLookupBuilder =
new JoinHashLookupBuilder<TRightInput, TRightKey, TKey>(rightHashStream[i], _keyComparer);
outputStream[i] = new HashJoinQueryOperatorEnumerator<TLeftInput, TLeftKey, TRightInput, TRightKey, TKey, TOutput, TOutputKey>(
leftHashStream[i], rightLookupBuilder, _resultSelector, outputKeyBuilder, cancellationToken);
}
outputRecipient.Receive(outputStream);
}
internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TLeftInput> leftResults = LeftChild.Open(settings, false);
QueryResults<TRightInput> rightResults = RightChild.Open(settings, false);
return new BinaryQueryOperatorResults(leftResults, rightResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TLeftInput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token);
IEnumerable<TRightInput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token);
return wrappedLeftChild.Join(
wrappedRightChild, _leftKeySelector, _rightKeySelector, _resultSelector, _keyComparer);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
/// <summary>
/// Class to build a HashJoinHashLookup of right elements for use in Join operations.
/// </summary>
/// <typeparam name="TElement"></typeparam>
/// <typeparam name="TOrderKey"></typeparam>
/// <typeparam name="THashKey"></typeparam>
internal class JoinHashLookupBuilder<TElement, TOrderKey, THashKey> : HashLookupBuilder<TElement, TOrderKey, THashKey>
{
private readonly QueryOperatorEnumerator<Pair<TElement, THashKey>, TOrderKey> _dataSource; // data source. For building.
private readonly IEqualityComparer<THashKey> _keyComparer; // An optional key comparison object.
internal JoinHashLookupBuilder(QueryOperatorEnumerator<Pair<TElement, THashKey>, TOrderKey> dataSource, IEqualityComparer<THashKey> keyComparer)
{
Debug.Assert(dataSource != null);
_dataSource = dataSource;
_keyComparer = keyComparer;
}
public override HashJoinHashLookup<THashKey, TElement, TOrderKey> BuildHashLookup(CancellationToken cancellationToken)
{
HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>> lookup =
new HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>>(_keyComparer);
JoinBaseHashBuilder baseHashBuilder = new JoinBaseHashBuilder(lookup);
BuildBaseHashLookup(_dataSource, baseHashBuilder, cancellationToken);
return new JoinHashLookup(lookup);
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_dataSource != null);
_dataSource.Dispose();
}
/// <summary>
/// Adds TElement,TOrderKey values to a HashLookup of HashLookupValueLists.
/// </summary>
private struct JoinBaseHashBuilder : IBaseHashBuilder<TElement, TOrderKey>
{
private readonly HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>> _base;
public JoinBaseHashBuilder(HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>> baseLookup)
{
Debug.Assert(baseLookup != null);
_base = baseLookup;
}
public bool Add(THashKey hashKey, TElement element, TOrderKey orderKey)
{
HashLookupValueList<TElement, TOrderKey> currentValue = default(HashLookupValueList<TElement, TOrderKey>);
if (!_base.TryGetValue(hashKey, ref currentValue))
{
currentValue = new HashLookupValueList<TElement, TOrderKey>(element, orderKey);
_base.Add(hashKey, currentValue);
return false;
}
else
{
if (currentValue.Add(element, orderKey))
{
// We need to re-store this element because the pair is a value type.
_base[hashKey] = currentValue;
}
return true;
}
}
}
/// <summary>
/// A wrapper for the HashLookup returned by JoinHashLookupBuilder.
///
/// Since Join operations do not require a default, this just passes the call on to the base lookup.
/// </summary>
private class JoinHashLookup : HashJoinHashLookup<THashKey, TElement, TOrderKey>
{
private readonly HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>> _base;
internal JoinHashLookup(HashLookup<THashKey, HashLookupValueList<TElement, TOrderKey>> baseLookup)
{
Debug.Assert(baseLookup != null);
_base = baseLookup;
}
public override bool TryGetValue(THashKey key, ref HashLookupValueList<TElement, TOrderKey> value)
{
return _base.TryGetValue(key, ref value);
}
}
}
}
| |
// 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 CompareEqualInt32()
{
var test = new SimpleBinaryOpTest__CompareEqualInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualInt32 testClass)
{
var result = Sse2.CompareEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqualInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__CompareEqualInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareEqual(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareEqual(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqualInt32();
var result = Sse2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareEqualInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] == right[0]) ? unchecked((int)(-1)) : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((int)(-1)) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Int32>(Vector128<Int32>, Vector128<Int32>): {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;
}
}
}
}
| |
//
// ContiguousTernarySearchTree.cs
//
// Author:
// Scott Peterson <[email protected]>
//
// Copyright (c) 2009 Scott Peterson
//
// 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.Collections.Internal;
namespace Mono.Collections.DataStructures
{
// Genus: Trie (a.k.a. Prefix Tree)
//
// Species: Radix Tree (a.k.a. Crit Bit Trie a.k.a. Patricia Trie)
//
// Unique Features: Child nodes are stored in a binary tree
//
// Capabilities: Value lookup by string key
//
// Pros: Fast lookup, low memory overhead, good locality of reference
//
// Cons: Readonly, 65,536 maximum capacity, 2,147,483,648 maximum structure size
//
// Biography:
// The contiguous ternary search tree is a memory-efficient data structure to store values
// by unique key strings. It is based on a radix tree (also know as a crit bit trie) which
// is a kind of trie. The radix tree is stored in a single char array, hense "contigugous."
// By storing the entire structure in a single array, we improve the locality of memory and
// therefore increase the likelihood of CPU cache hits. As with all tries, the lookup time
// for a key is constant with respect to the number of elements in the structure. Tries
// almost always out-perform hash tables for lookup when the trie fits into system memory.
// The radix tree is also highly compact. The amount of memory consumed by the entire tree
// is often less than the amount of memory required to contain all of the constituent keys.
// The children of each node in the tree are stored in balanced binary trees, hense
// "ternary." This allows for O(log n) search time among the children of a given node. The
// added complexity of a binary search is only warented if the average number of children
// per node is high (4 or higher). When the system constructs the radix tree, it analyses
// the structure of the tree and chooses between ContiguousTernarySearchTree and
// ContiguousRadixTree (a similar structure, but with an ordered list of children as
// opposed to a binary tree) as appropriate. The use of a char array limits the number of
// total items the tree can store to 65,536 (the number of values representable with 16
// bits). To store more than 65,536 items, use a pointer-based trie.
public sealed class ContiguousTernarySearchTree<T>
{
// The children of a node in the prefix tree are
// arranged into a balanced binary tree which
// branches first to the left. Trees are stored
// contiguously in the array as follows: a node
// in the prefix tree is immediately followed in
// memory by its entire subtree, starting with
// the root node of its children's binary tree.
// Nodes in a binary tree are immediately
// followed in memory first by the entire left
// subtree, then the entire right subtree.
//
// The first element of a node is the length of
// the node's string. The node's string
// follows. The element after the string
// contains the number of child nodes in the radix
// tree. If this number is 0, the next element
// indexes into the value array for the value of
// the key string at that location in the tree. If
// the node's string has no length (meaning that a
// key is stored in the tree which is the prefix
// of another key), then the first element of the
// node is 0 and the node immediately afterward
// indexes into the value array. If the node has
// children to the left in the binary tree, the
// element after the radix tree child count is the
// relative index of the child to the left in the
// binary tree. If the node has children to the
// right in the binary tree, the element after the
// left binary tree child relative index is the
// relative index of the child to the right in the
// binary tree. (A node has a right binary tree
// child only if it has a left binary tree child).
// The first element of the array is the number of
// children in the prefix tree under the root node.
readonly char[] tree;
readonly T[] values;
public ContiguousTernarySearchTree (IList<KeyValuePair<string, T>> keyValuePairs)
{
// The CSRT has a very compact, very specific layout in memory.
// The construction of this layout is non-trivial. We start with
// a sorted list of key-value pairs.
var children = new List<SinglyLinkedList<char>> ();
var values = new List<T> (keyValuePairs.Count);
var index = 0;
// We collect the root nodes of the radix tree
do {
children.Add (Probe (keyValuePairs, values, ref index, 0, keyValuePairs.Count));
} while (index < keyValuePairs.Count);
// The radix tree starts with the number of children under
// the root, followed by the binary tree of those children.
var root = new SinglyLinkedList<char> ();
root.AddFirst ((char)children.Count);
root.AddLast (CreateBinaryTree (children));
// We render the value and tree arrays to their final form.
this.values = values.ToArray ();
tree = new char[root.Count];
var node = root.First;
for (var i = 0; i < root.Count; i++) {
tree[i] = node.Value;
node = node.Next;
}
}
static SinglyLinkedList<char> Probe (IList<KeyValuePair<string, T>> keyValuePairs, List<T> values, ref int index, int keyIndex, int probeLimit)
{
var pair = keyValuePairs[index];
var key = pair.Key;
var key_length = key.Length;
if (keyIndex == key_length) {
// We are trying to probe a subtree which doesn't exist.
// This will only happen if there are duplicate keys.
throw new ArgumentException ("There is a duplicate key in the set.");
}
// We probe ahead to see how many other keys share
// the first character (the prefix).
var probe_depth = GetProbeDepth (keyValuePairs, index, keyIndex, probeLimit);
if (probe_depth - 1 == index) {
// Nothing else has this prefix, so we are at a leaf node.
// Leaf nodes begin with the length of the node's string,
// followed by the string, followed by 0, followed by
// the index of the matching value in the value array.
var leaf_node = new SinglyLinkedList<char> ();
leaf_node.AddLast ((char)(key_length - keyIndex));
for (var i = keyIndex; i < key_length; i++) {
leaf_node.AddLast (key[i]);
}
leaf_node.AddLast ((char)0);
leaf_node.AddLast ((char)values.Count);
values.Add (pair.Value);
index++;
// A leaf node has no children, so we return it.
return leaf_node;
}
// We know that there is a shared prefix but so far we have
// only looked at the first character. Now we extend the
// character we are looking at as long as the same depth
// of keys match. This will give us the full prefix.
var key_probe_index = keyIndex;
do {
key_probe_index++;
} while (key_probe_index < key_length && probe_depth == GetProbeDepth (keyValuePairs, index, key_probe_index, probeLimit));
// We now know the full prefix string for this node.
// Non-leaf nodes start with the length of the prefix
// string, followed by the prefix string, followed
// by the number of child nodes in the readix tree,
// followed by the relative offset of the left sub-
// node in this node's binary tree, followed by the
// relative offset of the right sub-node in this
// node's binary tree (if it exists).
var node = new SinglyLinkedList<char> ();
node.AddLast ((char)(key_probe_index - keyIndex));
for (var i = keyIndex; i < key_probe_index; i++) {
node.AddLast (key[i]);
}
var children = new List<SinglyLinkedList<char>> ();
if (key_probe_index == key_length) {
// The node's prefix string matches one of the
// keys, so we add a leaf node to this node's
// children.
var leaf_node = new SinglyLinkedList<char> ();
leaf_node.AddLast ((char)0);
leaf_node.AddLast ((char)values.Count);
values.Add (pair.Value);
index++;
children.Add (leaf_node);
}
// We recurse through the radix tree and collect
// the children of this node.
do {
children.Add (Probe (keyValuePairs, values, ref index, key_probe_index, probe_depth));
} while (index < probe_depth);
node.AddLast ((char)children.Count);
// We organize the children into a binary tree.
node.AddLast (CreateBinaryTree (children));
return node;
}
static int GetProbeDepth (IList<KeyValuePair<string, T>> keyValuePairs, int index, int keyIndex, int probeLimit)
{
var character = keyValuePairs[index].Key[keyIndex];
do {
index++;
} while (index < probeLimit &&
keyIndex < keyValuePairs[index].Key.Length &&
character == keyValuePairs[index].Key[keyIndex]);
return index;
}
static SinglyLinkedList<char> CreateBinaryTree (List<SinglyLinkedList<char>> children)
{
var midpoint = children.Count >> 0x1;
return CreateBinaryTree (children, midpoint, midpoint, children.Count - midpoint - 1);
}
static SinglyLinkedList<char> CreateBinaryTree (List<SinglyLinkedList<char>> nodes, int index, int left, int right)
{
var node = nodes[index];
var insertion_point = node.First;
var length = insertion_point.Value;
for (var i = 0; i <= length; i++) {
insertion_point = insertion_point.Next;
}
if (insertion_point.Value == 0) {
insertion_point = insertion_point.Next;
length++;
}
length++;
if (left > 0) {
var new_left = left >> 0x1;
var new_index = (index - left) + new_left;
var left_node = CreateBinaryTree (nodes, new_index, new_left, left - new_left - 1);
var relative_index = node.Count - length;
if (right > 0) {
relative_index++;
}
node.AddAfter ((char)relative_index, insertion_point);
insertion_point = insertion_point.Next;
length++;
node.AddLast (left_node);
}
if (right > 0) {
var new_right = right >> 0x1;
var new_index = (index + right) - new_right;
var right_node = CreateBinaryTree (nodes, new_index, right - new_right - 1, new_right);
var relative_index = node.Count - length;
node.AddAfter ((char)relative_index, insertion_point);
node.AddLast (right_node);
}
return node;
}
// Time Complexity:
// O(1) worst case WRT to number of values in the structure
// O(n) worst case WRT the length of 'key'
public T this[string key] {
get {
var value_index = GetValueIndex (key);
if (value_index == -1) {
throw new KeyNotFoundException ();
}
return values[value_index];
}
}
// Time Complexity:
// O(1) worst case WRT to number of values in the structure
// O(n) worst case WRT the length of 'key'
public bool ContainsKey (string key)
{
return GetValueIndex (key) != -1;
}
int GetValueIndex (string key)
{
var key_index = 0;
var tree_index = 1;
// The first element of the tree has the
// number of children under the root.
// These children are in a balanced binary
// tree. We split this number into the left
// and right space of the binary tree.
var left = tree[0] >> 1;
var right = tree[0] - left - 1;
while (true) {
// The first element of a node is the length
// of the node's string.
var length = tree[tree_index];
// If the node has a string, we step into it.
// TODO if we really wanted to, we could use
// a goto in an else to this if and jump
// over a comparison or two, but goto is EVIL.
// What to do, what to do, what to do!
if (length != 0) {
tree_index++;
if (key_index == key.Length || key[key_index] < tree[tree_index]) {
// The key would be to our left
// in the binary tree.
if (left == 0) {
// There is nothing to our left in the
// binary tree, so the key does not exist.
return -1;
}
// We move left in the binary tree.
tree_index += length;
if (tree[tree_index] == 0) {
// If the node has no children, we need
// to skip over the element containing
// the value index.
tree_index++;
}
tree_index++;
tree_index += tree[tree_index];
// We split the left and right values
// If we get strapped for registers, we can do:
// right = (left >> 0x1) + (left & 0x1) - 1;
// var new_left = left >> 0x1;
// right = left - new_left - 1;
right = (left >> 0x1) + (left & 0x1) - 1;
left >>= 0x1;
// Step ahead
continue;
} else if (key[key_index] > tree[tree_index]) {
// The key would be to our right
// in the binary tree.
if (right == 0) {
// There is nothing to our right in the
// binary tree, so the key does not exist.
return -1;
}
// We move right in the binary tree.
tree_index += length;
if (tree[tree_index] == 0) {
// If the node has no children, we need
// to skip over the element containing
// the value index.
tree_index++;
}
if (left != 0) {
// If there is space on the right, we need
// to skip over the element containing the
// right node relative index.
tree_index++;
}
tree_index++;
tree_index += tree[tree_index];
// We split the left and right values
// If we get strapped for registers, we can do:
// left = (right >> 0x1) + (right & 0x1) - 1;
// var new_right = right >> 0x1;
// left = right - new_right - 1;
left = (right >> 0x1) + (right & 0x1) - 1;
right >>= 0x1;
// Step ahead
continue;
} else {
// The key must match this node, so we
// check the whole thing.
tree_index++;
key_index++;
length--;
while (length != 0) {
if (key_index == key.Length) {
// We have consumed the input string
// and no such key exists.
return -1;
}
if (tree[tree_index] != key[key_index]) {
// The input string does not match
// the rest of the prefix so the
// key does not exist.
return -1;
}
tree_index++;
key_index++;
length--;
}
}
}
var children = tree[tree_index];
// The node matches the input and
// tree_index is positioned on the
// number of children under this
// node in the radix tree.
if (children == 0) {
// We have reached the end of the tree.
if (key_index == key.Length) {
// And we have consumed all of the
// input string, so we have a match!
// The next element in the tree indexes
// into the value array.
return tree[tree_index + 1];
} else {
// There is more input string, but no
// more tree! The key does not exist.
return -1;
}
} else {
// We are at a non-key prefix node in the radix
// tree. Children of this node are stored in a
// balanced binary tree.
// The root node of that binary tree is next up
// in the array.
tree_index++;
if (left != 0) {
// If there is something to our left, we need
// to skip over its relative index.
tree_index++;
}
if (right != 0) {
// If there is something to our right, we need
// to skip over its relative index.
tree_index++;
}
// We split the child count into the left and
// right space of the new binary tree.
left = children >> 1;
right = children - left - 1;
}
}
}
}
}
| |
using System;
using System.Runtime.Serialization;
using System.Threading;
using OpenADK.Library;
using OpenADK.Library.Impl;
using OpenADK.Library.Infra;
using OpenADK.Library.us.Student;
using OpenADK.Util;
using NUnit.Framework;
using Library.UnitTesting.Framework;
namespace Library.Nunit.US.Impl
{
/// <summary>
/// Summary description for MessageDispatcherTests.
/// </summary>
[TestFixture]
public class MessageDispatcherTests : InMemoryProtocolTest
{
//private Agent fAgent;
//private ZoneImpl fZone;
private static String MSG_GUID = "MESSAGE_DISPATCH_TESTS";
//[SetUp]
//public void setUp()
//{
// Adk.Initialize();
// fAgent = new TestAgent();
// fAgent.Initialize();
// fZone = new TestZoneImpl("test", "http://127.0.0.1/test", fAgent, null); //:7080
//}
[Test]
public void testNormalEvent()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.Normal);
SubscriptionOptions options = new SubscriptionOptions();
fZone.SetSubscriber(handler, objType, options);
fZone.Connect(ProvisioningFlags.Register);
//fZone.SetSubscriber(handler, objType, null);
SIF_Event evnt = createSIF_Event(objType);
assertNormalHandling(handler, evnt, fZone);
}
[Test]
public void testEventThrowsNullPointerException()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowNullPointerException);
SubscriptionOptions options = new SubscriptionOptions();
fZone.SetSubscriber(handler, objType, options);
fZone.Connect(ProvisioningFlags.Register);
//
//fZone.SetSubscriber(handler, objType, null);
SIF_Event evnt = createSIF_Event(objType);
AssertExceptionHandling(handler, evnt, fZone, typeof(NullReferenceException));
}
[Test]
public void testEventThrowsException()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowException);
SubscriptionOptions options = new SubscriptionOptions();
fZone.SetSubscriber(handler, objType, options);
fZone.Connect(ProvisioningFlags.Register);
//
// fZone.SetSubscriber(handler, objType, null);
SIF_Event evnt = createSIF_Event(objType);
AssertExceptionHandling(handler, evnt, fZone, typeof(AdkException));
}
[Test]
public void testSIFRetryEvent()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowADKRetryException);
fZone.SetSubscriber(handler, objType, null);
SIF_Event evnt = createSIF_Event(objType);
fZone.Connect(ProvisioningFlags.Register);
AssertRetryHandling(handler, evnt, fZone);
}
[Test]
public void testUndeliverableRetryEvent()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowSIFRetryException);
fAgent.ErrorHandler = handler;
SIF_Event evnt = createSIF_Event(objType);
fZone.Connect(ProvisioningFlags.Register);
AssertRetryHandling(handler, evnt, fZone);
}
private SIF_Event createSIF_Event(IElementDef objType)
{
SIF_Event evnt = new SIF_Event();
evnt.Header.SIF_SourceId = "foo";
SIF_ObjectData sod = new SIF_ObjectData();
SIF_EventObject obj = new SIF_EventObject();
obj.ObjectName = objType.Name;
sod.SIF_EventObject = obj;
evnt.SIF_ObjectData = sod;
obj.Action = EventAction.Add.ToString();
Object eventObject = null;
try
{
eventObject = ClassFactory.CreateInstance(objType.FQClassName);
}
catch (Exception cfe)
{
throw new AdkException("Unable to create instance of " + objType.Name, fZone, cfe);
}
obj.AddChild(objType, (SifElement)eventObject);
return evnt;
}
// TODO: Implement these test methods from the Java ADK unit tests
/*
public void testQueryResults() throws ADKException
{
TestState requestState = new TestState( ADK.makeGUID() );
ElementDef objType = SifDtd.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_NORMAL_HANDLING );
handler.RequestStateObject = requestState;
fZone.setQueryResults( handler, objType );
SIF_Response r = createSIF_Response( objType, true, requestState );
assertNormalHandling( handler, r, fZone );
assertRequestCacheCleared( r );
}
public void testQueryResultsTwoPackets() throws ADKException
{
TestState requestState = new TestState( ADK.makeGUID() );
ElementDef objType = SifDtd.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_NORMAL_HANDLING );
handler.RequestStateObject = requestState;
fZone.setQueryResults( handler, objType );
SIF_Response r = createSIF_Response( objType, true, requestState );
// Process first packet
r.setSIF_PacketNumber( "1" );
r.setSIF_MorePackets( "Yes" );
assertNormalHandling( handler, r, fZone );
// Process first packet
r.setSIF_PacketNumber( "2" );
r.setSIF_MorePackets( "No" );
assertNormalHandling( handler, r, fZone );
assertRequestCacheCleared( r );
}
public void testQueryResultsTwoPacketsFirstError() throws ADKException
{
TestState requestState = new TestState( ADK.makeGUID() );
ElementDef objType = SifDtd.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_THROW_EXCEPTION );
handler.RequestStateObject = requestState;
fZone.setQueryResults( handler, objType );
SIF_Response r = createSIF_Response( objType, true, requestState );
// Process first packet
r.setSIF_PacketNumber( "1" );
r.setSIF_MorePackets( "Yes" );
// The first packet is going to throw an exception
boolean exceptionThrown = false;
try
{
assertNormalHandling( handler, r, fZone );
}
catch( Exception ex )
{
exceptionThrown = true;
}
assertEquals( "An Exception should have been thrown", true, exceptionThrown );
// Process second packet
r.setSIF_PacketNumber( "2" );
r.setSIF_MorePackets( "No" );
handler.Behavior = ErrorMessageHandler.BVR_NORMAL_HANDLING;
assertNormalHandling( handler, r, fZone );
// Now the RequestCache should no longer contain the specified object
assertRequestCacheCleared( r );
}
public void testQueryResultsTwoPacketsFirstRetry() throws ADKException
{
TestState requestState = new TestState( ADK.makeGUID() );
ElementDef objType = SifDtd.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_THROW_ADKEXCEPTION_RETRY );
handler.RequestStateObject = requestState;
fZone.setQueryResults( handler, objType );
SIF_Response r = createSIF_Response( objType, true, requestState );
// Process first packet
r.setSIF_PacketNumber( "1" );
r.setSIF_MorePackets( "Yes" );
// The first packet is going to throw an exception with a retry
assertRetryHandling( handler, r, fZone );
// Now process it again without an exception
handler.Behavior = ErrorMessageHandler.BVR_NORMAL_HANDLING;
assertNormalHandling(handler, r, fZone);
// Process second packet
r.setSIF_PacketNumber( "2" );
r.setSIF_MorePackets( "No" );
handler.Behavior = ErrorMessageHandler.BVR_NORMAL_HANDLING;
assertNormalHandling( handler, r, fZone );
// Now the RequestCache should no longer contain the specified object
assertRequestCacheCleared( r );
}
*/
[Test]
public void testADKRetryQueryResults()
{
TestState requestState = new TestState(Adk.MakeGuid());
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowADKRetryException);
handler.RequestStateObject = requestState;
fZone.SetQueryResults(handler, objType, null );
fZone.Connect(ProvisioningFlags.Register);
SIF_Response r = createSIF_Response(objType, true, requestState);
AssertRetryHandling(handler, r, fZone);
// Now, dispatch a second time. This time the dispatching should work correctly, including
// custom state
handler.Behavior = ErrorMessageHandler.HandlerBehavior.Normal;
assertNormalHandling(handler, r, fZone);
assertRequestCacheCleared(r);
}
[Test]
public void testQueryResultsNoCache()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.Normal);
fZone.SetQueryResults(handler, objType, null );
fZone.Connect(ProvisioningFlags.Register);
SIF_Response r = createSIF_Response(objType, false, null);
assertNormalHandling(handler, r, fZone);
assertRequestCacheCleared(r);
}
[Test]
public void testADKRetryQueryResultsNoCache()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowADKRetryException);
fZone.SetQueryResults(handler, objType, null );
fZone.Connect(ProvisioningFlags.Register);
SIF_Response r = createSIF_Response(objType, false, null);
AssertRetryHandling(handler, r, fZone);
// Now, dispatch a second time. This time the dispatching should work correctly, including
// custom state
handler.Behavior = ErrorMessageHandler.HandlerBehavior.Normal;
assertNormalHandling(handler, r, fZone);
assertRequestCacheCleared(r);
}
[Test]
public void testSIFRetryQueryResultsNoCache()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowSIFRetryException);
fZone.SetQueryResults(handler, objType, null );
fZone.Connect(ProvisioningFlags.Register);
SIF_Response r = createSIF_Response(objType, false, null);
AssertRetryHandling(handler, r, fZone);
// Now, dispatch a second time. This time the dispatching should work correctly, including
// custom state
handler.Behavior = ErrorMessageHandler.HandlerBehavior.Normal;
assertNormalHandling(handler, r, fZone);
assertRequestCacheCleared(r);
}
[Test]
public void testSIFRetryQueryResults()
{
TestState requestState = new TestState(Adk.MakeGuid());
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowSIFRetryException);
handler.RequestStateObject = requestState;
fZone.SetQueryResults(handler, objType, null);
fZone.Connect(ProvisioningFlags.Register);
SIF_Response r = createSIF_Response(objType, true, requestState);
AssertRetryHandling(handler, r, fZone);
// Now, dispatch a second time. This time the dispatching should work correctly, including
// custom state
handler.Behavior = ErrorMessageHandler.HandlerBehavior.Normal;
assertNormalHandling(handler, r, fZone);
assertRequestCacheCleared(r);
}
[Test]
public void testADKRetryEvent()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowADKRetryException);
// SifContext ctxt = SifContext.Create("SIF_SUBSCRIBE");
// SubscriptionOptions options = new SubscriptionOptions(ctxt);
fZone.SetSubscriber(handler, objType, null);
SIF_Event evnt = createSIF_Event(objType);
fZone.Connect(ProvisioningFlags.Register);
AssertRetryHandling(handler, evnt, fZone);
}
[Test]
public void testADKRetryPublish()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowADKRetryException);
fZone.SetPublisher(handler, objType, null);
fZone.Connect(ProvisioningFlags.Register);
AssertRetryHandling(handler, createSIF_Request(objType), fZone);
}
[Test]
public void testSIFRetryPublish()
{
IElementDef objType = StudentDTD.STUDENTCONTACT;
ErrorMessageHandler handler =
new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowSIFRetryException);
fZone.SetPublisher(handler, objType, null);
fZone.Connect(ProvisioningFlags.Register);
AssertRetryHandling(handler, createSIF_Request(objType), fZone);
}
// TODO: Implement
/*
[Test]
public void testReportPublishSIFExceptionAfterReportInfo()
{
ElementDef objType = SifDtd.SIF_REPORTOBJECT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_SET_REPORT_INFO_THROW_EXCEPTION );
fZone.setReportPublisher( handler, ADKFlags.PROV_NONE);
TestProtocolHandler testProto = new TestProtocolHandler();
testProto.open(fZone);
MessageDispatcher testDispatcher = new MessageDispatcher( fZone );
fZone.setDispatcher(testDispatcher);
fZone.setProto(testProto);
testDispatcher.dispatch( createSIF_Request( objType, ADK.makeGUID(), fZone ) );
String msg = testProto.readMsg();
assertNull(testProto.readMsg());
fZone.log.info(msg);
SIFParser parser = SIFParser.newInstance();
SIFElement element = parser.parse(new StringReader(msg), fZone);
assertTrue(element instanceof SIF_Response);
SIF_Response response = (SIF_Response) element;
assertTrue(response.getSIF_Error() != null);
assertTrue(response.getSIF_Error().getSIF_Desc().startsWith("Blah"));
}
public void testReportPublishSIFExceptionAfterReportInfo() throws ADKException, IOException
{
ElementDef objType = SifDtd.SIF_REPORTOBJECT;
ErrorMessageHandler handler = new ErrorMessageHandler( ErrorMessageHandler.BVR_SET_REPORT_INFO_THROW_EXCEPTION );
fZone.setReportPublisher( handler, ADKFlags.PROV_NONE);
TestProtocolHandler testProto = new TestProtocolHandler();
testProto.open(fZone);
MessageDispatcher testDispatcher = new MessageDispatcher( fZone );
fZone.setDispatcher(testDispatcher);
fZone.setProto(testProto);
testDispatcher.dispatch( createSIF_Request( objType, ADK.makeGUID(), fZone ) );
String msg = testProto.readMsg();
assertNull(testProto.readMsg());
fZone.log.info(msg);
SIFParser parser = SIFParser.newInstance();
SIFElement element = parser.parse(new StringReader(msg), fZone);
assertTrue(element instanceof SIF_Response);
SIF_Response response = (SIF_Response) element;
assertTrue(response.getSIF_Error() != null);
assertTrue(response.getSIF_Error().getSIF_Desc().startsWith("Blah"));
}
*/
private SIF_Request createSIF_Request(IElementDef objType)
{
SIF_Request request = new SIF_Request();
request.Header.SIF_MsgId = MSG_GUID;
request.Header.SIF_SourceId = "foo";
request.SIF_MaxBufferSize = 32768;
request.AddSIF_Version(new SIF_Version(Adk.SifVersion.ToString()));
SIF_Query q = new SIF_Query();
SIF_QueryObject sqo = new SIF_QueryObject();
sqo.ObjectName = objType.Name;
q.SIF_QueryObject = sqo;
request.SIF_Query = q;
return request;
}
// TODO: Implement
/*
private SIF_Request createSIF_Request( ElementDef objectType, String refId, Zone zone )
{
SIF_Request request = new SIF_Request();
request.getHeader().setSIF_MsgId( MSG_GUID );
request.getHeader().setSIF_SourceId( "foo" );
request.setSIF_MaxBufferSize("32768");
request.setSIF_Version( ADK.getSIFVersion().toString() );
Query query = new Query(objectType);
query.addCondition(SifDtd.SIF_REPORTOBJECT_REFID, Condition.EQ, refId);
SIF_Query q = SIFPrimitives.createSIF_Query(query, zone);
SIF_QueryObject sqo = new SIF_QueryObject();
sqo.setObjectName( objectType.name() );
q.setSIF_QueryObject(sqo);
request.setSIF_Query(q);
return request;
}
*/
private SIF_Response createSIF_Response(IElementDef objType, bool storeInRequestCache, ISerializable stateObject)
{
SIF_Request req = createSIF_Request(objType);
if (storeInRequestCache)
{
Query q = new Query(objType);
q.UserData = stateObject;
RequestCache.GetInstance(fAgent).StoreRequestInfo(req, q, fZone);
}
SIF_Response resp = new SIF_Response();
resp.SIF_RequestMsgId = req.Header.SIF_MsgId;
SIF_ObjectData sod = new SIF_ObjectData();
resp.SIF_ObjectData = sod;
Object responseObject = null;
try
{
responseObject = ClassFactory.CreateInstance(objType.FQClassName, false);
}
catch (Exception cfe)
{
throw new AdkException("Unable to create instance of " + objType.Name, fZone, cfe);
}
sod.AddChild((SifElement)responseObject);
return resp;
}
private void assertNormalHandling(ErrorMessageHandler handler, SifMessagePayload payload, ZoneImpl zone)
{
MessageDispatcher testDispatcher = new MessageDispatcher(zone);
int result = testDispatcher.dispatch(payload);
Assert.IsTrue(handler.wasCalled(), "Handler was not called");
Assert.AreEqual(1, result, "Result code should always be 1 because this version does not support SMB");
}
private void AssertExceptionHandling(ErrorMessageHandler handler, SifMessagePayload payload, ZoneImpl zone,
Type expectedExceptionType)
{
Exception exc = null;
try
{
assertNormalHandling(handler, payload, zone);
}
catch (Exception ex)
{
exc = ex;
Assert.IsTrue(handler.wasCalled(), "Handler was not called");
AdkMessagingException adkme = ex as AdkMessagingException;
Assert.IsNotNull(adkme,
"Expected an ADKMessagingException, but was " + ex.GetType().Name + ":" + ex.ToString());
Exception source = adkme;
Exception innerEx = null;
while( source.InnerException != null )
{
innerEx = source.InnerException;
source = innerEx;
}
Assert.IsNotNull(innerEx, "AdkMessaginException was thrown but inner exception was not set");
if (innerEx.GetType() != expectedExceptionType)
{
Assert.Fail("Exception thrown was not a " + expectedExceptionType.Name + ", but was " +
innerEx.GetType().Name + ":" + innerEx.ToString());
}
}
Assert.IsNotNull(exc, "An exception was not thrown by the handler");
AssertThreadIsOK();
}
private void AssertThreadIsOK()
{
try
{
Thread.Sleep(10);
}
catch (Exception ex)
{
Assert.Fail("Tried to sleep the thread, but an Exception was thrown: " + ex.GetType().Name + " : " +
ex.ToString());
}
}
private void AssertRetryHandling(ErrorMessageHandler handler, SifMessagePayload payload, ZoneImpl zone)
{
try
{
assertNormalHandling(handler, payload, zone);
}
catch (SifException ex)
{
Assert.IsTrue(handler.wasCalled(), "Handler was not called");
Assert.AreEqual(SifErrorCategoryCode.Transport, ex.ErrorCategory,
"SIF Error category should be 10: " + ex.Message);
}
Assert.IsTrue(handler.wasCalled(), "Handler was not called");
AssertThreadIsOK();
}
private void assertRequestCacheCleared(SIF_Response r)
{
// Now the RequestCache should no longer contain the specified object
IRequestInfo inf = RequestCache.GetInstance(fAgent).LookupRequestInfo(r.SIF_RequestMsgId, fZone);
Assert.IsNull(inf, "RequestInfo should be removed from the cache");
}
}
}
| |
namespace EnergyTrading.Mdm.Test.Contracts.Validators
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using EnergyTrading.Data;
using EnergyTrading.Mdm.Contracts;
using EnergyTrading.Mdm.Contracts.Validators;
using EnergyTrading.Mdm.ServiceHost.Unity.Configuration;
using EnergyTrading.Validation;
using Microsoft.Practices.Unity;
using Moq;
using NUnit.Framework;
using DateRange = EnergyTrading.DateRange;
using SourceSystem = EnergyTrading.Mdm.Contracts.SourceSystem;
[TestFixture]
public partial class SourceSystemValidatorFixture : Fixture
{
[Test]
public void ValidatorResolution()
{
var container = CreateContainer();
var meConfig = new SimpleMappingEngineConfiguration(container);
meConfig.Configure();
var repository = new Mock<IRepository>();
container.RegisterInstance(repository.Object);
var config = new SourceSystemConfiguration(container);
config.Configure();
var validator = container.Resolve<IValidator<SourceSystem>>("sourcesystem");
// Assert
Assert.IsNotNull(validator, "Validator resolution failed");
}
[Test]
public void ValidSourceSystemPasses()
{
// Assert
var start = new DateTime(1999, 1, 1);
var system = new Mdm.SourceSystem { Name = "Test" };
var systemList = new List<Mdm.SourceSystem> { system };
var systemRepository = new Mock<IRepository>();
var repository = new StubValidatorRepository();
systemRepository.Setup(x => x.Queryable<Mdm.SourceSystem>()).Returns(systemList.AsQueryable());
var identifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Test",
Identifier = "1",
StartDate = start.AddHours(-10),
EndDate = start.AddHours(-5)
};
var validatorEngine = new Mock<IValidatorEngine>();
var validator = new SourceSystemValidator(validatorEngine.Object, repository);
var sourcesystem = new SourceSystem { Details = new EnergyTrading.Mdm.Contracts.SourceSystemDetails{Name = "Test"}, Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { identifier } };
this.AddRelatedEntities(sourcesystem);
// Act
var violations = new List<IRule>();
var result = validator.IsValid(sourcesystem, violations);
// Assert
Assert.IsTrue(result, "Validator failed");
Assert.AreEqual(0, violations.Count, "Violation count differs");
}
[Test]
public void OverlapsRangeFails()
{
// Assert
var start = new DateTime(1999, 1, 1);
var finish = new DateTime(2020, 12, 31);
var validity = new DateRange(start, finish);
var system = new Mdm.SourceSystem { Name = "Test" };
var sourcesystemMapping = new SourceSystemMapping { System = system, MappingValue = "1", Validity = validity };
var list = new List<SourceSystemMapping> { sourcesystemMapping };
var repository = new Mock<IRepository>();
repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable());
var systemList = new List<Mdm.SourceSystem>();
var systemRepository = new Mock<IRepository>();
systemRepository.Setup(x => x.Queryable<Mdm.SourceSystem>()).Returns(systemList.AsQueryable());
var overlapsRangeIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Test",
Identifier = "1",
StartDate = start.AddHours(10),
EndDate = start.AddHours(15)
};
var identifierValidator = new NexusIdValidator<SourceSystemMapping>(repository.Object);
var validatorEngine = new Mock<IValidatorEngine>();
validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
.Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
var validator = new SourceSystemValidator(validatorEngine.Object, repository.Object);
var sourcesystem = new SourceSystem { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { overlapsRangeIdentifier } };
// Act
var violations = new List<IRule>();
var result = validator.IsValid(sourcesystem, violations);
// Assert
Assert.IsFalse(result, "Validator succeeded");
}
[Test]
public void BadSystemFails()
{
// Assert
var start = new DateTime(1999, 1, 1);
var finish = new DateTime(2020, 12, 31);
var validity = new DateRange(start, finish);
var system = new Mdm.SourceSystem { Name = "Test" };
var sourcesystemMapping = new SourceSystemMapping { System = system, MappingValue = "1", Validity = validity };
var list = new List<SourceSystemMapping> { sourcesystemMapping };
var repository = new Mock<IRepository>();
repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable());
var badSystemIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Jim",
Identifier = "1",
StartDate = start.AddHours(-10),
EndDate = start.AddHours(-5)
};
var identifierValidator = new NexusIdValidator<SourceSystemMapping>(repository.Object);
var validatorEngine = new Mock<IValidatorEngine>();
validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
.Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
var validator = new SourceSystemValidator(validatorEngine.Object, repository.Object);
var sourcesystem = new SourceSystem { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { badSystemIdentifier } };
// Act
var violations = new List<IRule>();
var result = validator.IsValid(sourcesystem, violations);
// Assert
Assert.IsFalse(result, "Validator succeeded");
}
[Test]
public void ParentShouldNotBeSameAsEntity()
{
// Arrange
var parentId = 999;
var sourceSystem = NewSourceSystem("SameName", parentId);
var repository = new Mock<IRepository>();
repository.Setup(x => x.FindOne<Mdm.SourceSystem>(parentId))
.Returns(new Mdm.SourceSystem { Name = "SameName"});
// Act
var violations = new List<IRule>();
var validator = new SourceSystemValidator(new Mock<IValidatorEngine>().Object, repository.Object);
var result = validator.IsValid(sourceSystem, violations);
// Assert
Assert.IsFalse(result, "Validation should not have succeeded");
Assert.AreEqual(1, violations.Count);
Assert.AreEqual("Parent must not be same as entity", violations[0].Message);
}
partial void AddRelatedEntities(SourceSystem contract);
private SourceSystem NewSourceSystem(string name, int parentId)
{
var sourceSystem = new SourceSystem
{
Details =
{
Name = name,
Parent = new EntityId
{
Identifier = new MdmId
{
SystemName = "Nexus",
Identifier = parentId.ToString(CultureInfo.InvariantCulture),
IsMdmId = true
}
}
}
};
return sourceSystem;
}
}
}
| |
//
// AppleDeviceSource.cs
//
// Author:
// Alan McGovern <[email protected]>
// Phil Trimble <[email protected]>
// Andres G. Aragoneses <[email protected]>
//
// Copyright (C) 2010 Novell, Inc.
// Copyright (C) 2012 Phil Trimble
// Copyright (C) 2012 Andres G. Aragoneses
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Hyena;
using Hyena.Query;
using Banshee.Base;
using Banshee.Collection.Database;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Hardware;
using Banshee.Sources;
using Banshee.I18n;
using Banshee.Playlist;
using Banshee.Collection;
namespace Banshee.Dap.AppleDevice
{
public class AppleDeviceSource : DapSource, IBatchScrobblerSource
{
GPod.Device Device {
get; set;
}
IVolume Volume {
get; set;
}
GPod.ITDB MediaDatabase {
get; set;
}
private Dictionary<long, AppleDeviceTrackInfo> tracks_map = new Dictionary<long, AppleDeviceTrackInfo> (); // FIXME: EPIC FAIL
public event EventHandler<ScrobblingBatchEventArgs> ReadyToScrobble;
#region Device Setup/Dispose
public override void DeviceInitialize (IDevice device, bool force)
{
Volume = device as IVolume;
if (Volume == null) {
throw new InvalidDeviceException ();
}
if (!Volume.IsMounted && device.MediaCapabilities != null && device.MediaCapabilities.IsType ("ipod")) {
Hyena.Log.Information ("Found potential unmounted iDevice, trying to mount it now");
Volume.Mount ();
}
if (!Volume.IsMounted) {
Hyena.Log.Information ("AppleDeviceSource is ignoring unmounted volume " + Volume.Name);
throw new InvalidDeviceException ();
}
Device = new GPod.Device (Volume.MountPoint);
if (GPod.ITDB.GetControlPath (Device) == null) {
throw new InvalidDeviceException ();
}
base.DeviceInitialize (device, force);
Name = Volume.Name;
SupportsPlaylists = true;
SupportsPodcasts = Device.SupportsPodcast;
SupportsVideo = Device.SupportsVideo;
Initialize ();
GPod.ITDB.InitIpod (Volume.MountPoint, Device.IpodInfo == null ? null : Device.IpodInfo.ModelNumber, Name);
// HACK: ensure that m4a, and mp3 are set as accepted by the device; bgo#633552
AcceptableMimeTypes = (AcceptableMimeTypes ?? new string [0]).Union (new string [] { "taglib/m4a", "taglib/mp3" }).ToArray ();
// FIXME: Properly parse the device, color and generation and don't use the fallback strings
// IpodInfo is null on Macos formated ipods. I don't think we can really do anything with them
// but they get loaded as UMS devices if we throw an NRE here.
if (Device.IpodInfo != null) {
AddDapProperty (Catalog.GetString ("Device"), Device.IpodInfo.ModelString);
AddDapProperty (Catalog.GetString ("Generation"), Device.IpodInfo.GenerationString);
}
// FIXME
//AddDapProperty (Catalog.GetString ("Color"), "black");
AddDapProperty (Catalog.GetString ("Capacity"), string.Format ("{0:0.00}GB", BytesCapacity / 1024.0 / 1024.0 / 1024.0));
AddDapProperty (Catalog.GetString ("Available"), string.Format ("{0:0.00}GB", BytesAvailable / 1024.0 / 1024.0 / 1024.0));
AddDapProperty (Catalog.GetString ("Serial number"), Volume.Serial);
//AddDapProperty (Catalog.GetString ("Produced on"), ipod_device.ProductionInfo.DisplayDate);
//AddDapProperty (Catalog.GetString ("Firmware"), ipod_device.FirmwareVersion);
//string [] capabilities = new string [ipod_device.ModelInfo.Capabilities.Count];
//ipod_device.ModelInfo.Capabilities.CopyTo (capabilities, 0);
//AddDapProperty (Catalog.GetString ("Capabilities"), String.Join (", ", capabilities));
AddYesNoDapProperty (Catalog.GetString ("Supports cover art"), Device.SupportsArtwork);
AddYesNoDapProperty (Catalog.GetString ("Supports photos"), Device.SupportsPhoto);
}
public override void Dispose ()
{
//ThreadAssist.ProxyToMain (DestroyUnsupportedView);
CancelSyncThread ();
base.Dispose ();
}
// WARNING: This will be called from a thread!
protected override void Eject ()
{
base.Eject ();
CancelSyncThread ();
if (Volume.CanUnmount)
Volume.Unmount ();
if (Volume.CanEject)
Volume.Eject ();
Dispose ();
}
protected override bool CanHandleDeviceCommand (DeviceCommand command)
{
// Whats this for?
return false;
// try {
// SafeUri uri = new SafeUri (command.DeviceId);
// return IpodDevice.MountPoint.StartsWith (uri.LocalPath);
// } catch {
// return false;
// }
}
#endregion
#region Database Loading
// WARNING: This will be called from a thread!
protected override void LoadFromDevice ()
{
LoadFromDevice (false);
OnTracksAdded ();
}
private void LoadFromDevice (bool refresh)
{
tracks_map.Clear ();
if (refresh || MediaDatabase == null) {
if (MediaDatabase != null)
MediaDatabase.Dispose ();
try {
MediaDatabase = new GPod.ITDB (Device.Mountpoint);
} catch (Exception e) {
Log.Error ("iPod database could not be loaded, creating a new one", e);
if (GPod.ITDB.InitIpod (Volume.MountPoint, null, Volume.Name)) {
// this may throw again. In the future we need to implement some kind of alert
// mechanism to let the user know that something more serious is wrong with their
// apple device a la the other iPod extension.
MediaDatabase = new GPod.ITDB (Device.Mountpoint);
} else {
Log.Error ("Failed to init iPod database");
return;
}
}
}
if (MediaDatabase.MasterPlaylist == null) {
MediaDatabase.Playlists.Add (new GPod.Playlist (Name) {
IsMaster = true
});
}
if (SupportsPodcasts && MediaDatabase.PodcastsPlaylist == null) {
MediaDatabase.Playlists.Add (new GPod.Playlist (Catalog.GetString ("Podcasts")) {
IsPodcast = true
});
}
foreach (var ipod_track in MediaDatabase.Tracks) {
if (String.IsNullOrEmpty (ipod_track.IpodPath)) {
invalid_tracks_in_device.Enqueue (ipod_track);
continue;
}
try {
var track = new AppleDeviceTrackInfo (ipod_track);
if (!tracks_map.ContainsKey (track.TrackId)) {
track.PrimarySource = this;
track.Save (false);
tracks_map.Add (track.TrackId, track);
}
} catch (Exception e) {
Log.Error (e);
}
}
if (invalid_tracks_in_device.Count > 0) {
Log.Warning (String.Format ("Found {0} invalid tracks on the device", invalid_tracks_in_device.Count));
}
Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
@"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID)
SELECT ?, TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND ExternalID = ?");
foreach (var playlist in MediaDatabase.Playlists) {
if (playlist.IsMaster || playlist.IsPodcast)
continue;
PlaylistSource pl_src = new PlaylistSource (playlist.Name, this);
pl_src.Save ();
// We use the GPod.Track.DBID here b/c we just shoved it into ExternalID above when we loaded
// the tracks, however when we sync, the Track.DBID values may/will change.
foreach (var track in playlist.Tracks) {
// DBID will be stored in a long, so we need to cast it. See bgo#650011
ServiceManager.DbConnection.Execute (insert_cmd, pl_src.DbId, this.DbId, (long) track.DBID);
}
pl_src.UpdateCounts ();
AddChildSource (pl_src);
}
RaiseReadyToScrobble ();
}
#endregion
#region Source Cosmetics
internal string [] _GetIconNames ()
{
return GetIconNames ();
}
protected override string [] GetIconNames ()
{
string [] names = new string[4];
string prefix = "multimedia-player-";
//string shell_color = "green";
names[0] = "";
names[2] = "ipod-standard-color";
names[3] = "multimedia-player";
/*
switch ("grayscale") {
case "grayscale":
names[1] = "ipod-standard-monochrome";
break;
case "color":
names[1] = "ipod-standard-color";
break;
case "mini":
names[1] = String.Format ("ipod-mini-{0}", shell_color);
names[2] = "ipod-mini-silver";
break;
case "shuffle":
names[1] = String.Format ("ipod-shuffle-{0}", shell_color);
names[2] = "ipod-shuffle";
break;
case "nano":
case "nano3":
names[1] = String.Format ("ipod-nano-{0}", shell_color);
names[2] = "ipod-nano-white";
break;
case "video":
names[1] = String.Format ("ipod-video-{0}", shell_color);
names[2] = "ipod-video-white";
break;
case "classic":
case "touch":
case "phone":
default:
break;
}
*/
names[1] = names[1] ?? names[2];
names[1] = prefix + names[1];
names[2] = prefix + names[2];
return names;
}
public override void Rename (string name)
{
if (!CanRename) {
return;
}
try {
MediaDatabase.MasterPlaylist.Name = name;
base.Rename (name);
} catch (Exception e) {
Log.Error ("Trying to change iPod name", e);
}
}
public override bool CanRename {
get { return !(IsAdding || IsDeleting || IsReadOnly); }
}
public override long BytesUsed {
get { return (long) Volume.Capacity - Volume.Available; }
}
public override long BytesCapacity {
get { return (long) Volume.Capacity; }
}
#endregion
#region Syncing
public override void UpdateMetadata (DatabaseTrackInfo track)
{
lock (sync_mutex) {
AppleDeviceTrackInfo ipod_track;
if (!tracks_map.TryGetValue (track.TrackId, out ipod_track)) {
return;
}
ipod_track.UpdateInfo (track);
tracks_to_update.Enqueue (ipod_track);
}
}
protected override void OnTracksChanged (params QueryField[] fields)
{
if (tracks_to_update.Count > 0 && !Sync.Syncing) {
QueueSync ();
}
base.OnTracksChanged (fields);
}
protected override void OnTracksAdded ()
{
if (!IsAdding && tracks_to_add.Count > 0 && !Sync.Syncing) {
QueueSync ();
}
base.OnTracksAdded ();
}
protected override void OnTracksDeleted ()
{
if (!IsDeleting && tracks_to_remove.Count > 0 && !Sync.Syncing) {
QueueSync ();
}
base.OnTracksDeleted ();
}
private Queue<AppleDeviceTrackInfo> tracks_to_add = new Queue<AppleDeviceTrackInfo> ();
private Queue<AppleDeviceTrackInfo> tracks_to_update = new Queue<AppleDeviceTrackInfo> ();
private Queue<AppleDeviceTrackInfo> tracks_to_remove = new Queue<AppleDeviceTrackInfo> ();
private Queue<GPod.Track> invalid_tracks_in_device = new Queue<GPod.Track> ();
private uint sync_timeout_id = 0;
private object sync_timeout_mutex = new object ();
private object sync_mutex = new object ();
private object write_mutex = new object ();
private Thread sync_thread;
private AutoResetEvent sync_thread_wait;
private bool sync_thread_dispose = false;
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source);
}
public override bool CanAddTracks {
get {
return base.CanAddTracks;
}
}
public override bool IsReadOnly {
get { return false; }//!database_supported; }
}
public override string BaseDirectory {
get { return Volume.MountPoint; }
}
public override void Import ()
{
Banshee.ServiceStack.ServiceManager.Get<LibraryImportManager> ().Enqueue (GPod.ITDB.GetMusicPath (Device));
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
Banshee.IO.File.Copy (track.Uri, uri, false);
}
protected override bool DeleteTrack (DatabaseTrackInfo track)
{
lock (sync_mutex) {
if (!tracks_map.ContainsKey (track.TrackId)) {
return true;
}
var ipod_track = tracks_map[track.TrackId];
if (ipod_track != null) {
tracks_to_remove.Enqueue (ipod_track);
}
return true;
}
}
private void DeleteTrack (GPod.Track track, bool removeFile)
{
foreach (var playlist in MediaDatabase.Playlists) {
playlist.Tracks.Remove (track);
}
if (SupportsPodcasts &&
track.MediaType == GPod.MediaType.Podcast &&
MediaDatabase.PodcastsPlaylist != null) {
MediaDatabase.PodcastsPlaylist.Tracks.Remove (track);
}
MediaDatabase.MasterPlaylist.Tracks.Remove (track);
MediaDatabase.Tracks.Remove (track);
if (removeFile) {
Banshee.IO.File.Delete (new SafeUri (GPod.ITDB.GetLocalPath (Device, track)));
}
}
protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
lock (sync_mutex) {
if (track.PrimarySourceId == DbId) {
return;
}
if (track.Duration.Equals (TimeSpan.Zero)) {
throw new Exception (Catalog.GetString ("Track duration is zero"));
}
AppleDeviceTrackInfo ipod_track = new AppleDeviceTrackInfo (track);
ipod_track.Uri = fromUri;
ipod_track.PrimarySource = this;
tracks_to_add.Enqueue (ipod_track);
}
}
public override void SyncPlaylists ()
{
if (!IsReadOnly && Monitor.TryEnter (sync_mutex)) {
try {
PerformSync ();
} finally {
Monitor.Exit (sync_mutex);
}
}
}
private void QueueSync ()
{
lock (sync_timeout_mutex) {
if (sync_timeout_id > 0) {
Application.IdleTimeoutRemove (sync_timeout_id);
}
sync_timeout_id = Application.RunTimeout (150, PerformSync);
}
}
private void CancelSyncThread ()
{
Thread thread = sync_thread;
lock (sync_mutex) {
if (sync_thread != null && sync_thread_wait != null) {
sync_thread_dispose = true;
sync_thread_wait.Set ();
}
}
if (thread != null) {
thread.Join ();
}
}
private bool PerformSync ()
{
lock (sync_mutex) {
if (sync_thread == null) {
sync_thread_wait = new AutoResetEvent (false);
sync_thread = new Thread (new ThreadStart (PerformSyncThread));
sync_thread.Name = "iPod Sync Thread";
sync_thread.IsBackground = false;
sync_thread.Priority = ThreadPriority.Lowest;
sync_thread.Start ();
}
sync_thread_wait.Set ();
lock (sync_timeout_mutex) {
sync_timeout_id = 0;
}
return false;
}
}
private void PerformSyncThread ()
{
try {
while (true) {
sync_thread_wait.WaitOne ();
if (sync_thread_dispose) {
break;
}
PerformSyncThreadCycle ();
}
lock (sync_mutex) {
sync_thread_dispose = false;
sync_thread_wait.Close ();
sync_thread_wait = null;
sync_thread = null;
}
} catch (Exception e) {
Log.Error (e);
}
}
private void UpdateProgress (UserJob job, string message, int completed, int total)
{
job.Status = string.Format (message, completed, total);
job.Progress = completed / (double) total;
}
private void PerformSyncThreadCycle ()
{
Hyena.Log.Debug ("Starting AppleDevice sync thread cycle");
var progressUpdater = new UserJob (Catalog.GetString ("Syncing iPod"),
Catalog.GetString ("Preparing to synchronize..."), GetIconNames ());
progressUpdater.Register ();
MediaDatabase.StartSync ();
SyncTracksToAdd (progressUpdater);
SyncTracksToUpdate (progressUpdater);
SyncTracksToRemove (progressUpdater);
SyncTracksToPlaylists ();
SyncDatabase (progressUpdater);
MediaDatabase.StopSync ();
progressUpdater.Finish ();
Hyena.Log.Debug ("Ending AppleDevice sync thread cycle");
}
void SyncTracksToAdd (UserJob progressUpdater)
{
string message = Catalog.GetString ("Adding track {0} of {1}");
int total = tracks_to_add.Count;
int i = 0;
while (tracks_to_add.Count > 0) {
AppleDeviceTrackInfo track = null;
lock (sync_mutex) {
total = tracks_to_add.Count + i;
track = tracks_to_add.Dequeue ();
}
try {
UpdateProgress (progressUpdater, message, ++i, total);
track.CommitToIpod (MediaDatabase);
track.Save (false);
tracks_map[track.TrackId] = track;
} catch (Exception e) {
Log.Error ("Cannot save track to the Apple device", e);
}
}
if (total > 0) {
OnTracksAdded ();
OnUserNotifyUpdated ();
}
}
void SyncTracksToUpdate (UserJob progressUpdater)
{
string message = Catalog.GetString ("Updating metadata in track {0} of {1}");
int total = tracks_to_update.Count;
while (tracks_to_update.Count > 0) {
AppleDeviceTrackInfo track = null;
lock (sync_mutex) {
track = tracks_to_update.Dequeue ();
}
try {
UpdateProgress (progressUpdater, message, total - tracks_to_update.Count, total);
track.CommitToIpod (MediaDatabase);
} catch (Exception e) {
Log.Error ("Cannot save track to iPod", e);
}
}
}
void SyncTracksToRemove (UserJob progressUpdater)
{
string message = Catalog.GetString ("Removing track {0} of {1}");
int total = tracks_to_remove.Count;
while (tracks_to_remove.Count > 0) {
AppleDeviceTrackInfo track = null;
lock (sync_mutex) {
track = tracks_to_remove.Dequeue ();
}
if (tracks_map.ContainsKey (track.TrackId)) {
tracks_map.Remove (track.TrackId);
}
try {
if (track.IpodTrack != null) {
UpdateProgress (progressUpdater, message, total - tracks_to_remove.Count, total);
DeleteTrack (track.IpodTrack, true);
} else {
Log.Error ("The ipod track was null");
}
} catch (Exception e) {
Log.Error ("Cannot remove track from iPod", e);
}
}
SyncRemovalOfInvalidTracks (progressUpdater);
}
void SyncRemovalOfInvalidTracks (UserJob progressUpdater)
{
string message = Catalog.GetString ("Cleaning up, removing invalid track {0} of {1}");
int total = invalid_tracks_in_device.Count;
while (invalid_tracks_in_device.Count > 0) {
try {
UpdateProgress (progressUpdater, message, total - invalid_tracks_in_device.Count, total);
DeleteTrack (invalid_tracks_in_device.Dequeue (), false);
} catch (Exception e) {
Log.Error ("Cannot remove invalid track from iPod", e);
}
}
}
void SyncTracksToPlaylists ()
{
if (!SupportsPlaylists) {
return;
}
// Remove playlists on the device
var device_playlists = new List<GPod.Playlist> (MediaDatabase.Playlists);
foreach (var playlist in device_playlists) {
if (!playlist.IsMaster && !playlist.IsPodcast) {
MediaDatabase.Playlists.Remove (playlist);
}
}
// Add playlists from Banshee to the device
foreach (Source child in Children) {
PlaylistSource from = child as PlaylistSource;
if (from != null && from.Count > 0) {
var playlist = new GPod.Playlist (from.Name);
MediaDatabase.Playlists.Add (playlist);
foreach (long track_id in ServiceManager.DbConnection.QueryEnumerable<long> (String.Format (
"SELECT CoreTracks.TrackID FROM {0} WHERE {1}",
from.DatabaseTrackModel.ConditionFromFragment, from.DatabaseTrackModel.Condition)))
{
if (tracks_map.ContainsKey (track_id)) {
playlist.Tracks.Add (tracks_map[track_id].IpodTrack);
}
}
}
}
}
void SyncDatabase (UserJob progressUpdater)
{
try {
string message = Catalog.GetString ("Writing media database");
UpdateProgress (progressUpdater, message, 1, 1);
lock (write_mutex) {
MediaDatabase.Write ();
}
Log.Information ("Wrote iPod database");
} catch (Exception e) {
Log.Error ("Failed to save iPod database", e);
}
}
public bool SyncNeeded {
get {
lock (sync_mutex) {
return tracks_to_add.Count > 0 ||
tracks_to_update.Count > 0 ||
tracks_to_remove.Count > 0;
}
}
}
public override bool HasEditableTrackProperties {
get {
// we want child sources to be able to edit metadata and the
// savetrackmetadataservice to take in account this source
return true;
}
}
#endregion
#region Scrobbling
private void RaiseReadyToScrobble ()
{
var handler = ReadyToScrobble;
if (handler != null) {
var recent_plays = new ScrobblingBatchEventArgs {
ScrobblingBatch = GatherRecentPlayInfo ()
};
if (recent_plays.ScrobblingBatch.Count != 0) {
handler (this, recent_plays);
// We must perform a write to clear out the recent playcount information so we do not
// submit duplicate plays on subsequent invocations.
lock (write_mutex) {
MediaDatabase.Write ();
}
}
}
}
private IDictionary<TrackInfo, IList<DateTime>> GatherRecentPlayInfo ()
{
var recent_plays = new Dictionary <TrackInfo, IList<DateTime>> ();
foreach (var ipod_track in MediaDatabase.Tracks) {
if (String.IsNullOrEmpty (ipod_track.IpodPath) || ipod_track.RecentPlayCount == 0) {
continue;
}
IList<DateTime> playtimes = GenerateFakePlaytimes (ipod_track);
recent_plays [new AppleDeviceTrackInfo (ipod_track)] = playtimes;
}
return recent_plays;
}
// Apple products do not save DateTime info for each track play, only a total
// sum of number of plays (playcount) of each track.
private IList<DateTime> GenerateFakePlaytimes (GPod.Track track)
{
IList<DateTime> playtimes = new List<DateTime> ();
//FIXME: avoid sequences of overlapping playtimes?
DateTime current_playtime = track.TimePlayed;
for (int i = 0; i < track.RecentPlayCount; i++) {
playtimes.Add (current_playtime);
current_playtime -= TimeSpan.FromMilliseconds (track.TrackLength);
}
return playtimes;
}
#endregion
}
}
| |
using System;
using System.IO;
using static MLAPI.Serialization.Arithmetic;
namespace MLAPI.Serialization
{
/// <summary>
/// A buffer that can be used at the bit level
/// </summary>
public class NetworkBuffer : Stream
{
private const int k_InitialCapacity = 16;
private const float k_InitialGrowthFactor = 2.0f;
private byte[] m_Target;
/// <summary>
/// A buffer that supports writing data smaller than a single byte. This buffer also has a built-in compression algorithm that can (optionally) be used to write compressed data.
/// </summary>
/// <param name="capacity">Initial capacity of buffer in bytes.</param>
/// <param name="growthFactor">Factor by which buffer should grow when necessary.</param>
public NetworkBuffer(int capacity, float growthFactor)
{
m_Target = new byte[capacity];
GrowthFactor = growthFactor;
Resizable = true;
}
/// <summary>
/// A buffer that supports writing data smaller than a single byte. This buffer also has a built-in compression algorithm that can (optionally) be used to write compressed data.
/// </summary>
/// <param name="growthFactor">Factor by which buffer should grow when necessary.</param>
public NetworkBuffer(float growthFactor) : this(k_InitialCapacity, growthFactor) { }
/// <summary>
/// A buffer that supports writing data smaller than a single byte. This buffer also has a built-in compression algorithm that can (optionally) be used to write compressed data.
/// </summary>
/// <param name="capacity"></param>
public NetworkBuffer(int capacity) : this(capacity, k_InitialGrowthFactor) { }
/// <summary>
/// A buffer that supports writing data smaller than a single byte. This buffer also has a built-in compression algorithm that can (optionally) be used to write compressed data.
/// </summary>
public NetworkBuffer() : this(k_InitialCapacity, k_InitialGrowthFactor) { }
/// <summary>
/// A buffer that supports writing data smaller than a single byte. This buffer also has a built-in compression algorithm that can (optionally) be used to write compressed data.
/// NOTE: when using a pre-allocated buffer, the buffer will not grow!
/// </summary>
/// <param name="target">Pre-allocated buffer to write to</param>
public NetworkBuffer(byte[] target)
{
m_Target = target;
Resizable = false;
BitLength = (ulong)(target.Length << 3);
}
internal void SetTarget(byte[] target)
{
m_Target = target;
BitLength = (ulong)(target.Length << 3);
Position = 0;
}
/// <summary>
/// Whether or not the buffer will grow the buffer to accomodate more data.
/// </summary>
public bool Resizable { get; }
private float m_GrowthFactor;
/// <summary>
/// Factor by which buffer should grow when necessary.
/// </summary>
public float GrowthFactor { set { m_GrowthFactor = value <= 1 ? 1.5f : value; } get { return m_GrowthFactor; } }
/// <summary>
/// Whether or not buffeer supports reading. (Always true)
/// </summary>
public override bool CanRead => true;
/// <summary>
/// Whether or not or there is any data to be read from the buffer.
/// </summary>
public bool HasDataToRead => Position < Length;
/// <summary>
/// Whether or not seeking is supported by this buffer. (Always true)
/// </summary>
public override bool CanSeek => true;
/// <summary>
/// Whether or not this buffer can accept new data. NOTE: this will return true even if only fewer than 8 bits can be written!
/// </summary>
public override bool CanWrite => !BitAligned || Position < m_Target.LongLength || Resizable;
/// <summary>
/// Current buffer size. The buffer will not be resized (if possible) until Position is equal to Capacity and an attempt to write data is made.
/// </summary>
public long Capacity
{
get => m_Target.LongLength; // Optimized CeilingExact
set
{
if (value < Length) throw new ArgumentOutOfRangeException("New capcity too small!");
SetCapacity(value);
}
}
/// <summary>
/// The current length of data considered to be "written" to the buffer.
/// </summary>
public override long Length { get => Div8Ceil(BitLength); }
/// <summary>
/// The index that will be written to when any call to write data is made to this buffer.
/// </summary>
public override long Position { get => (long)(BitPosition >> 3); set => BitPosition = (ulong)value << 3; }
/// <summary>
/// Bit offset into the buffer that new data will be written to.
/// </summary>
public ulong BitPosition { get; set; }
/// <summary>
/// Length of data (in bits) that is considered to be written to the buffer.
/// </summary>
public ulong BitLength { get; private set; }
/// <summary>
/// Whether or not the current BitPosition is evenly divisible by 8. I.e. whether or not the BitPosition is at a byte boundary.
/// </summary>
public bool BitAligned { get => (BitPosition & 7) == 0; }
/// <summary>
/// Flush buffer. This does nothing since data is written directly to a byte buffer.
/// </summary>
public override void Flush() { } // NOP
/// <summary>
/// Grow buffer if possible. According to Max(bufferLength, 1) * growthFactor^Ceil(newContent/Max(bufferLength, 1))
/// </summary>
/// <param name="newContent">How many new values need to be accomodated (at least).</param>
//private void Grow(long newContent) => SetCapacity(Math.Max(target.LongLength, 1) * (long)Math.Pow(GrowthFactor, CeilingExact(newContent, Math.Max(target.LongLength, 1))));
/*
private void Grow(long newContent)
{
float grow = newContent / 64;
if (((long)grow) != grow) grow += 1;
SetCapacity((Capacity + 64) * (long)grow);
}
*/
private void Grow(long newContent)
{
long value = newContent + Capacity;
long newCapacity = value;
if (newCapacity < 256) newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < Capacity * 2) newCapacity = Capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(Capacity * 2) > int.MaxValue) newCapacity = value > int.MaxValue ? value : int.MaxValue;
SetCapacity(newCapacity);
}
/// <summary>
/// Read a misaligned byte. WARNING: If the current BitPosition <strong>isn't</strong> byte misaligned,
/// avoid using this method as it <strong>may</strong> cause an IndexOutOfBoundsException in such a case.
/// </summary>
/// <returns>A byte extracted from up to two separate buffer indices.</returns>
private byte ReadByteMisaligned()
{
int mod = (int)(BitPosition & 7);
return (byte)((m_Target[(int)Position] >> mod) | (m_Target[(int)(BitPosition += 8) >> 3] << (8 - mod)));
}
/// <summary>
/// Read an aligned byte from the buffer. It's recommended to not use this when the BitPosition is byte-misaligned.
/// </summary>
/// <returns>The byte stored at the current Position index</returns>
private byte ReadByteAligned() => m_Target[Position++];
/// <summary>
/// Read a byte as a byte. This is just for internal use so as to minimize casts (cuz they ugly af).
/// </summary>
/// <returns></returns>
internal byte ReadByteInternal() => BitAligned ? ReadByteAligned() : ReadByteMisaligned();
/// <summary>
/// Read a byte from the buffer. This takes into account possible byte misalignment.
/// </summary>
/// <returns>A byte from the buffer or, if a byte can't be read, -1.</returns>
public override int ReadByte() => HasDataToRead ? BitAligned ? ReadByteAligned() : ReadByteMisaligned() : -1;
/// <summary>
/// Peeks a byte without advancing the position
/// </summary>
/// <returns>The peeked byte</returns>
public int PeekByte() =>
HasDataToRead
? BitAligned ? m_Target[Position] :
(byte)((m_Target[(int)Position] >> (int)(BitPosition & 7)) | (m_Target[(int)(BitPosition + 8) >> 3] << (8 - (int)(BitPosition & 7))))
: -1;
/// <summary>
/// Read a single bit from the buffer.
/// </summary>
/// <returns>A bit in bool format. (True represents 1, False represents 0)</returns>
public bool ReadBit() => (m_Target[Position] & (1 << (int)(BitPosition++ & 7))) != 0;
/// <summary>
/// Read a subset of the buffer buffer and write the contents to the supplied buffer.
/// </summary>
/// <param name="buffer">Buffer to copy data to.</param>
/// <param name="offset">Offset into the buffer to write data to.</param>
/// <param name="count">How many bytes to attempt to read.</param>
/// <returns>Amount of bytes read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int tLen = Math.Min(count, (int)(m_Target.LongLength - Position) - ((BitPosition & 7) == 0 ? 0 : 1));
for (int i = 0; i < tLen; ++i) buffer[offset + i] = ReadByteInternal();
return tLen;
}
/// <summary>
/// Set position in buffer to read from/write to.
/// </summary>
/// <param name="offset">Offset from position origin.</param>
/// <param name="origin">How to calculate offset.</param>
/// <returns>The new position in the buffer that data will be written to.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return (long)((
BitPosition =
(
origin == SeekOrigin.Current ? offset > 0 ? Math.Min(BitPosition + ((ulong)offset << 3), (ulong)m_Target.Length << 3) :
(offset ^ SIGN_BIT_64) > Position ? 0UL :
BitPosition - (ulong)((offset ^ SIGN_BIT_64) << 3) :
origin == SeekOrigin.Begin ? (ulong)Math.Max(0, offset) << 3 :
(ulong)Math.Max(m_Target.Length - offset, 0) << 3
)) >> 3) + (long)((BitPosition & 1UL) | ((BitPosition >> 1) & 1UL) | ((BitPosition >> 2) & 1UL));
}
/// <summary>
/// Set the capacity of the internal buffer.
/// </summary>
/// <param name="value">New capacity of the buffer</param>
private void SetCapacity(long value)
{
if (!Resizable) throw new NotSupportedException("Can't resize non resizable buffer"); // Don't do shit because fuck you (comment by @GabrielTofvesson -TwoTen)
byte[] newTarg = new byte[value];
long len = Math.Min(value, m_Target.LongLength);
Buffer.BlockCopy(m_Target, 0, newTarg, 0, (int)len);
if (value < m_Target.LongLength) BitPosition = (ulong)value << 3;
m_Target = newTarg;
}
/// <summary>
/// Set length of data considered to be "written" to the buffer.
/// </summary>
/// <param name="value">New length of the written data.</param>
public override void SetLength(long value)
{
if (value < 0) throw new IndexOutOfRangeException("Cannot set a negative length!");
if (value > Capacity) Grow(value - Capacity);
BitLength = (ulong)value << 3;
BitPosition = Math.Min((ulong)value << 3, BitPosition);
}
/// <summary>
/// Write data from the given buffer to the internal buffer.
/// </summary>
/// <param name="buffer">Buffer to write from.</param>
/// <param name="offset">Offset in given buffer to start reading from.</param>
/// <param name="count">Amount of bytes to read copy from given buffer to buffer.</param>
public override void Write(byte[] buffer, int offset, int count)
{
// Check bit alignment. If misaligned, each byte written has to be misaligned
if (BitAligned)
{
if (Position + count >= m_Target.Length) Grow(count);
Buffer.BlockCopy(buffer, offset, m_Target, (int)Position, count);
Position += count;
}
else
{
if (Position + count + 1 >= m_Target.Length) Grow(count);
for (int i = 0; i < count; ++i) WriteMisaligned(buffer[offset + i]);
}
if (BitPosition > BitLength) BitLength = BitPosition;
}
/// <summary>
/// Write byte value to the internal buffer.
/// </summary>
/// <param name="value">The byte value to write.</param>
public override void WriteByte(byte value)
{
// Check bit alignment. If misaligned, each byte written has to be misaligned
if (BitAligned)
{
if (Position + 1 >= m_Target.Length) Grow(1);
m_Target[Position] = value;
Position += 1;
}
else
{
if (Position + 1 + 1 >= m_Target.Length) Grow(1);
WriteMisaligned(value);
}
if (BitPosition > BitLength) BitLength = BitPosition;
}
/// <summary>
/// Write a misaligned byte. NOTE: Using this when the bit position isn't byte-misaligned may cause an IndexOutOfBoundsException! This does not update the current Length of the buffer.
/// </summary>
/// <param name="value">Value to write</param>
private void WriteMisaligned(byte value)
{
int off = (int)(BitPosition & 7);
int shift1 = 8 - off;
m_Target[Position + 1] = (byte)((m_Target[Position + 1] & (0xFF << off)) | (value >> shift1));
m_Target[Position] = (byte)((m_Target[Position] & (0xFF >> shift1)) | (value << off));
BitPosition += 8;
}
/// <summary>
/// Write a byte (in an int format) to the buffer. This does not update the current Length of the buffer.
/// </summary>
/// <param name="value">Value to write</param>
private void WriteIntByte(int value) => WriteBytePrivate((byte)value);
/// <summary>
/// Write a byte (in a ulong format) to the buffer. This does not update the current Length of the buffer.
/// </summary>
/// <param name="byteValue">Value to write</param>
private void WriteULongByte(ulong byteValue) => WriteBytePrivate((byte)byteValue);
/// <summary>
/// Write a byte to the buffer. This does not update the current Length of the buffer.
/// </summary>
/// <param name="value">Value to write</param>
private void WriteBytePrivate(byte value)
{
if (Div8Ceil(BitPosition) == m_Target.LongLength) Grow(1);
if (BitAligned)
{
m_Target[Position] = value;
BitPosition += 8;
}
else WriteMisaligned(value);
UpdateLength();
}
/// <summary>
/// Write data from the given buffer to the internal buffer.
/// </summary>
/// <param name="buffer">Buffer to write from.</param>
public void Write(byte[] buffer) => Write(buffer, 0, buffer.Length);
/// <summary>
/// Write a single bit to the buffer
/// </summary>
/// <param name="bit">Value of the bit. True represents 1, False represents 0</param>
public void WriteBit(bool bit)
{
if (BitAligned && Position == m_Target.Length) Grow(1);
int offset = (int)(BitPosition & 7);
long pos = Position;
++BitPosition;
m_Target[pos] = (byte)(bit ? (m_Target[pos] & ~(1 << offset)) | (1 << offset) : (m_Target[pos] & ~(1 << offset)));
UpdateLength();
}
/// <summary>
/// Copy data from another stream
/// </summary>
/// <param name="s">Stream to copy from</param>
/// <param name="count">How many bytes to read. Set to value less than one to read until ReadByte returns -1</param>
public void CopyFrom(Stream s, int count = -1)
{
if (s is NetworkBuffer b) Write(b.m_Target, 0, count < 0 ? (int)b.Length : count);
else
{
long currentPosition = s.Position;
s.Position = 0;
int read;
bool readToEnd = count < 0;
while ((readToEnd || count-- > 0) && (read = s.ReadByte()) != -1)
WriteIntByte(read);
UpdateLength();
s.Position = currentPosition;
}
}
/// <summary>
/// Copies internal buffer to stream
/// </summary>
/// <param name="stream">The stream to copy to</param>
/// <param name="count">The maximum amount of bytes to copy. Set to value less than one to copy the full length</param>
#if !NET35
public new void CopyTo(Stream stream, int count = -1)
#else
public void CopyTo(Stream stream, int count = -1)
#endif
{
stream.Write(m_Target, 0, count < 0 ? (int)Length : count);
}
/// <summary>
/// Copies urnead bytes from the source stream
/// </summary>
/// <param name="s">The source stream to copy from</param>
/// <param name="count">The max amount of bytes to copy</param>
public void CopyUnreadFrom(Stream s, int count = -1)
{
long currentPosition = s.Position;
int read;
bool readToEnd = count < 0;
while ((readToEnd || count-- > 0) && (read = s.ReadByte()) != -1) WriteIntByte(read);
UpdateLength();
s.Position = currentPosition;
}
// TODO: Implement CopyFrom() for NetworkBuffer with bitCount parameter
/// <summary>
/// Copys the bits from the provided NetworkBuffer
/// </summary>
/// <param name="buffer">The buffer to copy from</param>
/// <param name="dataCount">The amount of data evel</param>
/// <param name="copyBits">Whether or not to copy at the bit level rather than the byte level</param>
public void CopyFrom(NetworkBuffer buffer, int dataCount, bool copyBits)
{
if (!copyBits)
{
CopyFrom(buffer, dataCount);
}
else
{
ulong count = dataCount < 0 ? buffer.BitLength : (ulong)dataCount;
if (buffer.BitLength < count) throw new IndexOutOfRangeException("Attempted to read more data than is available");
Write(buffer.GetBuffer(), 0, (int)(count >> 3));
for (int i = (int)(count & 7); i >= 0; --i) WriteBit(buffer.ReadBit());
}
}
/// <summary>
/// Update length of data considered to be "written" to the buffer.
/// </summary>
private void UpdateLength()
{
if (BitPosition > BitLength) BitLength = BitPosition;
}
/// <summary>
/// Get the internal buffer being written to by this buffer.
/// </summary>
/// <returns></returns>
public byte[] GetBuffer() => m_Target;
/// <summary>
/// Creates a copy of the internal buffer. This only contains the used bytes
/// </summary>
/// <returns>A copy of used bytes in the internal buffer</returns>
public byte[] ToArray()
{
byte[] copy = new byte[Length];
Buffer.BlockCopy(m_Target, 0, copy, 0, (int)Length);
return copy;
}
/// <summary>
/// Writes zeros to fill the last byte
/// </summary>
public void PadBuffer()
{
while (!BitAligned)
{
WriteBit(false);
}
}
/// <summary>
/// Reads zeros until the the buffer is byte aligned
/// </summary>
public void SkipPadBits()
{
while (!BitAligned)
{
ReadBit();
}
}
/// <summary>
/// Returns hex encoded version of the buffer
/// </summary>
/// <returns>Hex encoded version of the buffer</returns>
public override string ToString() => BitConverter.ToString(m_Target, 0, (int)Length);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class ReadTo_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random bytes to receive for parity testing
private const int numRndBytesParity = 8;
//The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
//The number of new lines to insert into the string not including the one at the end
//For BytesToRead testing
private const int DEFAULT_NUMBER_NEW_LINES = 2;
private const byte DEFAULT_NEW_LINE = (byte)'\n';
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verfifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine));
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.ReadTo(com1.NewLine);
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.WriteLine("");
if (com2.IsOpen)
com2.Close();
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesParity - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesParity - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndBytesParity];
char[] expectedChars = new char[numRndBytesParity];
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com2.Write(com1.NewLine);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + com1.NewLine.Length);
string strRead = com1.ReadTo(com1.NewLine);
char[] actualChars = strRead.ToCharArray();
Assert.Equal(expectedChars, actualChars);
if (1 < com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
}
com1.DiscardInBuffer();
bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n';
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
VerifyBytesToRead(1);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
VerifyBytesToRead(numRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine));
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine));
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.ReadTo(com.NewLine));
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesParity + 1]; //Plus one to accomidate the NewLineByte
char[] expectedChars = new char[numRndBytesParity + 1]; //Plus one to accomidate the NewLineByte
byte expectedByte;
//Genrate random characters without an parity error
for (int i = 0; i < numRndBytesParity; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
//Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedChars[parityErrorIndex] = (char)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
bytesToWrite[numRndBytesParity] = DEFAULT_NEW_LINE;
expectedChars[numRndBytesParity] = (char)DEFAULT_NEW_LINE;
VerifyRead(com1, com2, bytesToWrite, expectedChars);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES);
}
private void VerifyBytesToRead(int numBytesRead, int numNewLines)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte
ASCIIEncoding encoding = new ASCIIEncoding();
//Genrate random characters
for (int i = 0; i < numBytesRead; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
for (int i = 0; i < numNewLines; i++)
{
int newLineIndex;
newLineIndex = rndGen.Next(0, numBytesRead);
bytesToWrite[newLineIndex] = (byte)'\n';
expectedChars[newLineIndex] = (char)'\n';
}
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Open();
com2.Open();
bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE;
expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE;
VerifyRead(com1, com2, bytesToWrite, expectedChars);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
{
char[] actualChars = new char[expectedChars.Length];
int totalBytesRead;
int totalCharsRead;
int bytesToRead;
int lastIndexOfNewLine = -1;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
totalCharsRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
string rcvString;
try
{
rcvString = com1.ReadTo(com1.NewLine);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
char[] rcvBuffer = rcvString.ToCharArray();
int charsRead = rcvBuffer.Length;
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead);
int indexOfNewLine = Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1);
if (indexOfNewLine - (lastIndexOfNewLine + 1) != charsRead)
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead);
}
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead);
actualChars[totalCharsRead + charsRead] = (char)DEFAULT_NEW_LINE; //Add the NewLine char into actualChars
totalBytesRead += bytesRead + 1; //Plus 1 because we read the NewLine char
totalCharsRead += charsRead + 1; //Plus 1 because we read the NewLine char
lastIndexOfNewLine = indexOfNewLine;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}//End while there are more characters to read
Assert.Equal(expectedChars, actualChars);
}
#endregion
}
}
| |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class represents an entry in a Tar archive. It consists
/// of the entry's header, as well as the entry's File. Entries
/// can be instantiated in one of three ways, depending on how
/// they are to be used.
/// <p>
/// TarEntries that are created from the header bytes read from
/// an archive are instantiated with the TarEntry( byte[] )
/// constructor. These entries will be used when extracting from
/// or listing the contents of an archive. These entries have their
/// header filled in using the header bytes. They also set the File
/// to null, since they reference an archive entry not a file.</p>
/// <p>
/// TarEntries that are created from files that are to be written
/// into an archive are instantiated with the CreateEntryFromFile(string)
/// pseudo constructor. These entries have their header filled in using
/// the File's information. They also keep a reference to the File
/// for convenience when writing entries.</p>
/// <p>
/// Finally, TarEntries can be constructed from nothing but a name.
/// This allows the programmer to construct the entry by hand, for
/// instance when only an InputStream is available for writing to
/// the archive, and the header information is constructed from
/// other information. In this case the header fields are set to
/// defaults and the File is set to null.</p>
/// <see cref="TarHeader"/>
/// </summary>
public class TarEntry
{
#region Constructors
/// <summary>
/// Initialise a default instance of <see cref="TarEntry"/>.
/// </summary>
private TarEntry()
{
header = new TarHeader();
}
/// <summary>
/// Construct an entry from an archive's header bytes. File is set
/// to null.
/// </summary>
/// <param name = "headerBuffer">
/// The header bytes from a tar archive entry.
/// </param>
public TarEntry(byte[] headerBuffer)
{
header = new TarHeader();
header.ParseBuffer(headerBuffer);
}
/// <summary>
/// Construct a TarEntry using the <paramref name="header">header</paramref> provided
/// </summary>
/// <param name="header">Header details for entry</param>
public TarEntry(TarHeader header)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
this.header = (TarHeader)header.Clone();
}
#endregion Constructors
#region ICloneable Members
/// <summary>
/// Clone this tar entry.
/// </summary>
/// <returns>Returns a clone of this entry.</returns>
public object Clone()
{
var entry = new TarEntry();
entry.file = file;
entry.header = (TarHeader)header.Clone();
entry.Name = Name;
return entry;
}
#endregion ICloneable Members
/// <summary>
/// Construct an entry with only a <paramref name="name">name</paramref>.
/// This allows the programmer to construct the entry's header "by hand".
/// </summary>
/// <param name="name">The name to use for the entry</param>
/// <returns>Returns the newly created <see cref="TarEntry"/></returns>
public static TarEntry CreateTarEntry(string name)
{
var entry = new TarEntry();
TarEntry.NameTarHeader(entry.header, name);
return entry;
}
/// <summary>
/// Construct an entry for a file. File is set to file, and the
/// header is constructed from information from the file.
/// </summary>
/// <param name = "fileName">The file name that the entry represents.</param>
/// <returns>Returns the newly created <see cref="TarEntry"/></returns>
public static TarEntry CreateEntryFromFile(string fileName)
{
var entry = new TarEntry();
entry.GetFileTarHeader(entry.header, fileName);
return entry;
}
/// <summary>
/// Determine if the two entries are equal. Equality is determined
/// by the header names being equal.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with the current Object.</param>
/// <returns>
/// True if the entries are equal; false if not.
/// </returns>
public override bool Equals(object obj)
{
var localEntry = obj as TarEntry;
if (localEntry != null)
{
return Name.Equals(localEntry.Name);
}
return false;
}
/// <summary>
/// Derive a Hash value for the current <see cref="Object"/>
/// </summary>
/// <returns>A Hash code for the current <see cref="Object"/></returns>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Determine if the given entry is a descendant of this entry.
/// Descendancy is determined by the name of the descendant
/// starting with this entry's name.
/// </summary>
/// <param name = "toTest">
/// Entry to be checked as a descendent of this.
/// </param>
/// <returns>
/// True if entry is a descendant of this.
/// </returns>
public bool IsDescendent(TarEntry toTest)
{
if (toTest == null)
{
throw new ArgumentNullException(nameof(toTest));
}
return toTest.Name.StartsWith(Name, StringComparison.Ordinal);
}
/// <summary>
/// Get this entry's header.
/// </summary>
/// <returns>
/// This entry's TarHeader.
/// </returns>
public TarHeader TarHeader
{
get
{
return header;
}
}
/// <summary>
/// Get/Set this entry's name.
/// </summary>
public string Name
{
get
{
return header.Name;
}
set
{
header.Name = value;
}
}
/// <summary>
/// Get/set this entry's user id.
/// </summary>
public int UserId
{
get
{
return header.UserId;
}
set
{
header.UserId = value;
}
}
/// <summary>
/// Get/set this entry's group id.
/// </summary>
public int GroupId
{
get
{
return header.GroupId;
}
set
{
header.GroupId = value;
}
}
/// <summary>
/// Get/set this entry's user name.
/// </summary>
public string UserName
{
get
{
return header.UserName;
}
set
{
header.UserName = value;
}
}
/// <summary>
/// Get/set this entry's group name.
/// </summary>
public string GroupName
{
get
{
return header.GroupName;
}
set
{
header.GroupName = value;
}
}
/// <summary>
/// Convenience method to set this entry's group and user ids.
/// </summary>
/// <param name="userId">
/// This entry's new user id.
/// </param>
/// <param name="groupId">
/// This entry's new group id.
/// </param>
public void SetIds(int userId, int groupId)
{
UserId = userId;
GroupId = groupId;
}
/// <summary>
/// Convenience method to set this entry's group and user names.
/// </summary>
/// <param name="userName">
/// This entry's new user name.
/// </param>
/// <param name="groupName">
/// This entry's new group name.
/// </param>
public void SetNames(string userName, string groupName)
{
UserName = userName;
GroupName = groupName;
}
/// <summary>
/// Get/Set the modification time for this entry
/// </summary>
public DateTime ModTime
{
get
{
return header.ModTime;
}
set
{
header.ModTime = value;
}
}
/// <summary>
/// Get this entry's file.
/// </summary>
/// <returns>
/// This entry's file.
/// </returns>
public string File
{
get
{
return file;
}
}
/// <summary>
/// Get/set this entry's recorded file size.
/// </summary>
public long Size
{
get
{
return header.Size;
}
set
{
header.Size = value;
}
}
/// <summary>
/// Return true if this entry represents a directory, false otherwise
/// </summary>
/// <returns>
/// True if this entry is a directory.
/// </returns>
public bool IsDirectory
{
get
{
if (file != null)
{
return Directory.Exists(file);
}
if (header != null)
{
if ((header.TypeFlag == TarHeader.LF_DIR) || Name.EndsWith("/", StringComparison.Ordinal))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Fill in a TarHeader with information from a File.
/// </summary>
/// <param name="header">
/// The TarHeader to fill in.
/// </param>
/// <param name="file">
/// The file from which to get the header information.
/// </param>
public void GetFileTarHeader(TarHeader header, string file)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
if (file == null)
{
throw new ArgumentNullException(nameof(file));
}
this.file = file;
// bugfix from torhovl from #D forum:
string name = file;
// 23-Jan-2004 GnuTar allows device names in path where the name is not local to the current directory
if (name.IndexOf(Directory.GetCurrentDirectory(), StringComparison.Ordinal) == 0)
{
name = name.Substring(Directory.GetCurrentDirectory().Length);
}
/*
if (Path.DirectorySeparatorChar == '\\')
{
// check if the OS is Windows
// Strip off drive letters!
if (name.Length > 2)
{
char ch1 = name[0];
char ch2 = name[1];
if (ch2 == ':' && Char.IsLetter(ch1))
{
name = name.Substring(2);
}
}
}
*/
name = name.Replace(Path.DirectorySeparatorChar, '/');
// No absolute pathnames
// Windows (and Posix?) paths can start with UNC style "\\NetworkDrive\",
// so we loop on starting /'s.
while (name.StartsWith("/", StringComparison.Ordinal))
{
name = name.Substring(1);
}
header.LinkName = String.Empty;
header.Name = name;
if (Directory.Exists(file))
{
header.Mode = 1003; // Magic number for security access for a UNIX filesystem
header.TypeFlag = TarHeader.LF_DIR;
if ((header.Name.Length == 0) || header.Name[header.Name.Length - 1] != '/')
{
header.Name = header.Name + "/";
}
header.Size = 0;
}
else
{
header.Mode = 33216; // Magic number for security access for a UNIX filesystem
header.TypeFlag = TarHeader.LF_NORMAL;
header.Size = new FileInfo(file.Replace('/', Path.DirectorySeparatorChar)).Length;
}
header.ModTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)).ToUniversalTime();
header.DevMajor = 0;
header.DevMinor = 0;
}
/// <summary>
/// Get entries for all files present in this entries directory.
/// If this entry doesnt represent a directory zero entries are returned.
/// </summary>
/// <returns>
/// An array of TarEntry's for this entry's children.
/// </returns>
public TarEntry[] GetDirectoryEntries()
{
if ((file == null) || !Directory.Exists(file))
{
return new TarEntry[0];
}
string[] list = Directory.GetFileSystemEntries(file);
TarEntry[] result = new TarEntry[list.Length];
for (int i = 0; i < list.Length; ++i)
{
result[i] = TarEntry.CreateEntryFromFile(list[i]);
}
return result;
}
/// <summary>
/// Write an entry's header information to a header buffer.
/// </summary>
/// <param name = "outBuffer">
/// The tar entry header buffer to fill in.
/// </param>
public void WriteEntryHeader(byte[] outBuffer)
{
header.WriteHeader(outBuffer);
}
/// <summary>
/// Convenience method that will modify an entry's name directly
/// in place in an entry header buffer byte array.
/// </summary>
/// <param name="buffer">
/// The buffer containing the entry header to modify.
/// </param>
/// <param name="newName">
/// The new name to place into the header buffer.
/// </param>
static public void AdjustEntryName(byte[] buffer, string newName)
{
TarHeader.GetNameBytes(newName, buffer, 0, TarHeader.NAMELEN);
}
/// <summary>
/// Fill in a TarHeader given only the entry's name.
/// </summary>
/// <param name="header">
/// The TarHeader to fill in.
/// </param>
/// <param name="name">
/// The tar entry name.
/// </param>
static public void NameTarHeader(TarHeader header, string name)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
bool isDir = name.EndsWith("/", StringComparison.Ordinal);
header.Name = name;
header.Mode = isDir ? 1003 : 33216;
header.UserId = 0;
header.GroupId = 0;
header.Size = 0;
header.ModTime = DateTime.UtcNow;
header.TypeFlag = isDir ? TarHeader.LF_DIR : TarHeader.LF_NORMAL;
header.LinkName = String.Empty;
header.UserName = String.Empty;
header.GroupName = String.Empty;
header.DevMajor = 0;
header.DevMinor = 0;
}
#region Instance Fields
/// <summary>
/// The name of the file this entry represents or null if the entry is not based on a file.
/// </summary>
private string file;
/// <summary>
/// The entry's header information.
/// </summary>
private TarHeader header;
#endregion Instance Fields
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.StructuredData;
using Aurora.Framework.Capabilities;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using ChatSessionMember = Aurora.Framework.ChatSessionMember;
namespace Aurora.Modules.Chat
{
public class AuroraChatModule : ISharedRegionModule, IChatModule, IMuteListModule
{
private const int DEBUG_CHANNEL = 2147483647;
private const int DEFAULT_CHANNEL = 0;
private readonly Dictionary<UUID, ChatSession> ChatSessions = new Dictionary<UUID, ChatSession>();
private readonly Dictionary<UUID, MuteList[]> MuteListCache = new Dictionary<UUID, MuteList[]>();
private readonly List<IScene> m_scenes = new List<IScene>();
private IMuteListConnector MuteListConnector;
private IMessageTransferModule m_TransferModule;
internal IConfig m_config;
private bool m_enabled = true;
private float m_maxChatDistance = 100;
private int m_saydistance = 30;
private int m_shoutdistance = 256;
private bool m_useMuteListModule = true;
private int m_whisperdistance = 10;
public float MaxChatDistance
{
get { return m_maxChatDistance; }
set { m_maxChatDistance = value; }
}
public List<IScene> Scenes
{
get { return m_scenes; }
}
#region IChatModule Members
public int SayDistance
{
get { return m_saydistance; }
set { m_saydistance = value; }
}
public int ShoutDistance
{
get { return m_shoutdistance; }
set { m_shoutdistance = value; }
}
public int WhisperDistance
{
get { return m_whisperdistance; }
set { m_whisperdistance = value; }
}
public IConfig Config
{
get { return m_config; }
}
/// <summary>
/// Send the message from the prim to the avatars in the regions
/// </summary>
/// <param name = "sender"></param>
/// <param name = "c"></param>
public virtual void OnChatFromWorld(Object sender, OSChatMessage c)
{
// early return if not on public or debug channel
if (c.Channel != DEFAULT_CHANNEL && c.Channel != DEBUG_CHANNEL) return;
if (c.Range > m_maxChatDistance) //Check for max distance
c.Range = m_maxChatDistance;
DeliverChatToAvatars(ChatSourceType.Object, c);
}
public void SimChat(string message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, bool broadcast, float range, UUID ToAgentID, IScene scene)
{
OSChatMessage args = new OSChatMessage
{
Message = message,
Channel = channel,
Type = type,
Position = fromPos,
Range = range,
SenderUUID = fromID,
Scene = scene,
ToAgentID = ToAgentID
};
if (fromAgent)
{
IScenePresence user = scene.GetScenePresence(fromID);
if (user != null)
args.Sender = user.ControllingClient;
}
else
{
args.SenderObject = scene.GetSceneObjectPart(fromID);
}
args.From = fromName;
//args.
if (broadcast)
{
OnChatBroadcast(scene, args);
scene.EventManager.TriggerOnChatBroadcast(scene, args);
}
else
{
OnChatFromWorld(scene, args);
scene.EventManager.TriggerOnChatFromWorld(scene, args);
}
}
public void SimChat(string message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, IScene scene)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false, -1, UUID.Zero, scene);
}
/// <summary>
/// Say this message directly to a single person
/// </summary>
/// <param name = "message"></param>
/// <param name = "type"></param>
/// <param name = "fromPos"></param>
/// <param name = "fromName"></param>
/// <param name = "fromAgentID"></param>
public void SimChatBroadcast(string message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, UUID ToAgentID, IScene scene)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true, -1, ToAgentID, scene);
}
public virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c)
{
string fromName = c.From;
UUID fromID = UUID.Zero;
string message = c.Message;
IScene scene = c.Scene;
Vector3 fromPos = c.Position;
Vector3 regionPos = scene != null
? new Vector3(scene.RegionInfo.RegionLocX,
scene.RegionInfo.RegionLocY, 0)
: Vector3.Zero;
if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel;
IScenePresence avatar = (scene != null && c.Sender != null)
? scene.GetScenePresence(c.Sender.AgentId)
: null;
switch (sourceType)
{
case ChatSourceType.Agent:
if (scene != null)
{
if (avatar != null && message == "")
{
fromPos = avatar.AbsolutePosition;
fromName = avatar.Name;
fromID = c.Sender.AgentId;
//Always send this so it fires on typing start and end
IAttachmentsModule attMod = scene.RequestModuleInterface<IAttachmentsModule>();
if (attMod != null)
attMod.SendScriptEventToAttachments(avatar.UUID, "changed", new object[] {Changed.STATE});
}
else
fromID = c.SenderUUID;
}
else
fromID = c.SenderUUID;
break;
case ChatSourceType.Object:
fromID = c.SenderUUID;
break;
}
if (message.Length >= 1000) // libomv limit
message = message.Substring(0, 1000);
// MainConsole.Instance.DebugFormat("[CHAT]: DCTA: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, c.Type, sourceType);
foreach (IScenePresence presence in from s in m_scenes
select s.GetScenePresences() into ScenePresences
from presence in ScenePresences
where !presence.IsChildAgent
let fromRegionPos = fromPos + regionPos
let toRegionPos = presence.AbsolutePosition +
new Vector3(presence.Scene.RegionInfo.RegionLocX,
presence.Scene.RegionInfo.RegionLocY, 0)
let dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos)
where (c.Type != ChatTypeEnum.Whisper || dis <= m_whisperdistance) && (c.Type != ChatTypeEnum.Say || dis <= m_saydistance) && (c.Type != ChatTypeEnum.Shout || dis <= m_shoutdistance) && (c.Type != ChatTypeEnum.Custom || dis <= c.Range)
where sourceType != ChatSourceType.Agent || avatar == null || avatar.CurrentParcel == null || (avatar.CurrentParcelUUID == presence.CurrentParcelUUID || (!avatar.CurrentParcel.LandData.Private && !presence.CurrentParcel.LandData.Private))
select presence)
{
//If one of them is in a private parcel, and the other isn't in the same parcel, don't send the chat message
TrySendChatMessage(presence, fromPos, regionPos, fromID, fromName, c.Type, message, sourceType,
c.Range);
}
}
public virtual void TrySendChatMessage(IScenePresence presence, Vector3 fromPos, Vector3 regionPos,
UUID fromAgentID, string fromName, ChatTypeEnum type,
string message, ChatSourceType src, float Range)
{
if (type == ChatTypeEnum.Custom)
{
Vector3 fromRegionPos = fromPos + regionPos;
Vector3 toRegionPos = presence.AbsolutePosition +
new Vector3(presence.Scene.RegionInfo.RegionLocX,
presence.Scene.RegionInfo.RegionLocY, 0);
int dis = (int) Util.GetDistanceTo(toRegionPos, fromRegionPos);
//Set the best fitting setting for custom
if (dis < m_whisperdistance)
type = ChatTypeEnum.Whisper;
else if (dis > m_saydistance)
type = ChatTypeEnum.Shout;
else if (dis > m_whisperdistance && dis < m_saydistance)
type = ChatTypeEnum.Say;
}
// TODO: should change so the message is sent through the avatar rather than direct to the ClientView
presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName,
fromAgentID, (byte) src, (byte) ChatAudibleLevel.Fully);
}
#endregion
#region IChatModule
public List<IChatPlugin> AllChatPlugins = new List<IChatPlugin>();
public Dictionary<string, IChatPlugin> ChatPlugins = new Dictionary<string, IChatPlugin>();
public void RegisterChatPlugin(string main, IChatPlugin plugin)
{
if (!ChatPlugins.ContainsKey(main))
ChatPlugins.Add(main, plugin);
}
#endregion
#region IMuteListModule Members
/// <summary>
/// Get all the mutes from the database
/// </summary>
/// <param name = "AgentID"></param>
/// <param name = "Cached"></param>
/// <returns></returns>
public MuteList[] GetMutes(UUID AgentID, out bool Cached)
{
Cached = false;
MuteList[] List = new MuteList[0];
if (MuteListConnector == null)
return List;
if (!MuteListCache.TryGetValue(AgentID, out List))
List = MuteListConnector.GetMuteList(AgentID).ToArray();
else
Cached = true;
return List;
}
/// <summary>
/// Update the mute in the database
/// </summary>
/// <param name = "MuteID"></param>
/// <param name = "Name"></param>
/// <param name = "Flags"></param>
/// <param name = "AgentID"></param>
public void UpdateMuteList(UUID MuteID, string Name, int Flags, UUID AgentID)
{
if (MuteID == UUID.Zero)
return;
MuteList Mute = new MuteList
{
MuteID = MuteID,
MuteName = Name,
MuteType = Flags.ToString()
};
MuteListConnector.UpdateMute(Mute, AgentID);
MuteListCache.Remove(AgentID);
}
/// <summary>
/// Remove the given mute from the user's mute list in the database
/// </summary>
/// <param name = "MuteID"></param>
/// <param name = "Name"></param>
/// <param name = "AgentID"></param>
public void RemoveMute(UUID MuteID, string Name, UUID AgentID)
{
//Gets sent if a mute is not selected.
if (MuteID != UUID.Zero)
{
MuteListConnector.DeleteMute(MuteID, AgentID);
MuteListCache.Remove(AgentID);
}
}
#endregion
#region ISharedRegionModule Members
public virtual void Initialise(IConfigSource config)
{
m_config = config.Configs["AuroraChat"];
if (null == m_config)
{
MainConsole.Instance.Info("[AURORACHAT]: no config found, plugin disabled");
m_enabled = false;
return;
}
if (!m_config.GetBoolean("enabled", true))
{
MainConsole.Instance.Info("[AURORACHAT]: plugin disabled by configuration");
m_enabled = false;
return;
}
m_whisperdistance = m_config.GetInt("whisper_distance", m_whisperdistance);
m_saydistance = m_config.GetInt("say_distance", m_saydistance);
m_shoutdistance = m_config.GetInt("shout_distance", m_shoutdistance);
m_maxChatDistance = m_config.GetFloat("max_chat_distance", m_maxChatDistance);
m_useMuteListModule = (config.Configs["Messaging"].GetString("MuteListModule", "AuroraChatModule") ==
"AuroraChatModule");
}
public virtual void AddRegion(IScene scene)
{
if (!m_enabled)
return;
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClosingClient += OnClosingClient;
scene.EventManager.OnRegisterCaps += RegisterCaps;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
scene.EventManager.OnChatSessionRequest += OnChatSessionRequest;
scene.RegisterModuleInterface<IMuteListModule>(this);
scene.RegisterModuleInterface<IChatModule>(this);
FindChatPlugins();
//MainConsole.Instance.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName,
// m_whisperdistance, m_saydistance, m_shoutdistance);
}
public virtual void RegionLoaded(IScene scene)
{
if (!m_enabled) return;
if (m_useMuteListModule)
MuteListConnector = DataManager.DataManager.RequestPlugin<IMuteListConnector>();
if (m_TransferModule == null)
{
m_TransferModule =
scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
MainConsole.Instance.Error("[CONFERANCE MESSAGE]: No message transfer module, IM will not work!");
m_scenes.Clear();
m_enabled = false;
}
}
}
public virtual void RemoveRegion(IScene scene)
{
if (!m_enabled)
return;
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnClosingClient -= OnClosingClient;
scene.EventManager.OnRegisterCaps -= RegisterCaps;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
scene.EventManager.OnChatSessionRequest -= OnChatSessionRequest;
m_scenes.Remove(scene);
scene.UnregisterModuleInterface<IMuteListModule>(this);
scene.UnregisterModuleInterface<IChatModule>(this);
}
public virtual void Close()
{
}
public virtual void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "AuroraChatModule"; }
}
#endregion
private void FindChatPlugins()
{
AllChatPlugins = AuroraModuleLoader.PickupModules<IChatPlugin>();
foreach (IChatPlugin plugin in AllChatPlugins)
{
plugin.Initialize(this);
}
}
private void OnClosingClient(IClientAPI client)
{
client.OnChatFromClient -= OnChatFromClient;
client.OnMuteListRequest -= OnMuteListRequest;
client.OnUpdateMuteListEntry -= OnMuteListUpdate;
client.OnRemoveMuteListEntry -= OnMuteListRemove;
client.OnInstantMessage -= OnInstantMessage;
//Tell all client plugins that the user left
foreach (IChatPlugin plugin in AllChatPlugins)
{
plugin.OnClosingClient(client.AgentId, client.Scene);
}
}
public virtual void OnNewClient(IClientAPI client)
{
client.OnChatFromClient += OnChatFromClient;
client.OnMuteListRequest += OnMuteListRequest;
client.OnUpdateMuteListEntry += OnMuteListUpdate;
client.OnRemoveMuteListEntry += OnMuteListRemove;
client.OnInstantMessage += OnInstantMessage;
//Tell all the chat plugins about the new user
foreach (IChatPlugin plugin in AllChatPlugins)
{
plugin.OnNewClient(client);
}
}
/// <summary>
/// Set the correct position for the chat message
/// </summary>
/// <param name = "c"></param>
/// <returns></returns>
protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c)
{
IScenePresence avatar;
if ((avatar = c.Scene.GetScenePresence(c.Sender.AgentId)) != null)
c.Position = avatar.AbsolutePosition;
return c;
}
/// <summary>
/// New chat message from the client
/// </summary>
/// <param name = "sender"></param>
/// <param name = "c"></param>
protected virtual void OnChatFromClient(IClientAPI sender, OSChatMessage c)
{
c = FixPositionOfChatMessage(c);
// redistribute to interested subscribers
if(c.Message != "")
c.Scene.EventManager.TriggerOnChatFromClient(sender, c);
// early return if not on public or debug channel
if (c.Channel != DEFAULT_CHANNEL && c.Channel != DEBUG_CHANNEL) return;
// sanity check:
if (c.Sender == null)
{
MainConsole.Instance.ErrorFormat("[CHAT] OnChatFromClient from {0} has empty Sender field!", sender);
return;
}
//If the message is not blank, tell the plugins about it
if (c.Message != "")
{
#if (!ISWIN)
foreach (string pluginMain in ChatPlugins.Keys)
{
if (pluginMain == "all" || c.Message.StartsWith(pluginMain + "."))
{
IChatPlugin plugin;
ChatPlugins.TryGetValue(pluginMain, out plugin);
//If it returns false, stop the message from being sent
if (!plugin.OnNewChatMessageFromWorld(c, out c))
return;
}
}
#else
foreach (string pluginMain in ChatPlugins.Keys.Where(pluginMain => pluginMain == "all" || c.Message.StartsWith(pluginMain + ".")))
{
IChatPlugin plugin;
ChatPlugins.TryGetValue(pluginMain, out plugin);
//If it returns false, stop the message from being sent
if (!plugin.OnNewChatMessageFromWorld(c, out c))
return;
}
#endif
}
string Name2 = "";
if (sender is IClientAPI)
{
Name2 = (sender).Name;
}
c.From = Name2;
DeliverChatToAvatars(ChatSourceType.Agent, c);
}
protected virtual void OnChatBroadcast(Object sender, OSChatMessage c)
{
// unless the chat to be broadcast is of type Region, we
// drop it if its channel is neither 0 nor DEBUG_CHANNEL
if (c.Channel != DEFAULT_CHANNEL && c.Channel != DEBUG_CHANNEL && c.Type != ChatTypeEnum.Region) return;
ChatTypeEnum cType = c.Type;
if (c.Channel == DEBUG_CHANNEL)
cType = ChatTypeEnum.DebugChannel;
if (c.Range > m_maxChatDistance)
c.Range = m_maxChatDistance;
if (cType == ChatTypeEnum.SayTo)
//Change to something client can understand as SayTo doesn't exist except on the server
cType = ChatTypeEnum.Owner;
if (cType == ChatTypeEnum.Region)
cType = ChatTypeEnum.Say;
if (c.Message.Length > 1100)
c.Message = c.Message.Substring(0, 1000);
// broadcast chat works by redistributing every incoming chat
// message to each avatar in the scene.
string fromName = c.From;
UUID fromID = UUID.Zero;
ChatSourceType sourceType = ChatSourceType.Object;
if (null != c.Sender)
{
IScenePresence avatar = c.Scene.GetScenePresence(c.Sender.AgentId);
fromID = c.Sender.AgentId;
fromName = avatar.Name;
sourceType = ChatSourceType.Agent;
}
// MainConsole.Instance.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType);
c.Scene.ForEachScenePresence(
delegate(IScenePresence presence)
{
// ignore chat from child agents
if (presence.IsChildAgent) return;
IClientAPI client = presence.ControllingClient;
// don't forward SayOwner chat from objects to
// non-owner agents
if ((c.Type == ChatTypeEnum.Owner) &&
(null != c.SenderObject) &&
(c.SenderObject.OwnerID != client.AgentId))
return;
// don't forward SayTo chat from objects to
// non-targeted agents
if ((c.Type == ChatTypeEnum.SayTo) &&
(c.ToAgentID != client.AgentId))
return;
bool cached = false;
MuteList[] mutes = GetMutes(client.AgentId, out cached);
foreach(MuteList m in mutes)
if (m.MuteID == c.SenderUUID ||
(c.SenderObject != null && m.MuteID == c.SenderObject.ParentEntity.UUID))
return;
client.SendChatMessage(c.Message, (byte) cType,
new Vector3(client.Scene.RegionInfo.RegionSizeX*0.5f,
client.Scene.RegionInfo.RegionSizeY*0.5f, 30), fromName,
fromID,
(byte) sourceType, (byte) ChatAudibleLevel.Fully);
});
}
/// <summary>
/// Get all the mutes the client has set
/// </summary>
/// <param name = "client"></param>
/// <param name = "crc"></param>
private void OnMuteListRequest(IClientAPI client, uint crc)
{
if (!m_useMuteListModule)
return;
//Sends the name of the file being sent by the xfer module DO NOT EDIT!!!
string filename = "mutes" + client.AgentId.ToString();
byte[] fileData = new byte[0];
string invString = "";
int i = 0;
bool cached = false;
MuteList[] List = GetMutes(client.AgentId, out cached);
if (List == null)
return;
if (cached)
client.SendUseCachedMuteList();
Dictionary<UUID, bool> cache = new Dictionary<UUID, bool>();
foreach (MuteList mute in List)
{
cache[mute.MuteID] = true;
invString += (mute.MuteType + " " + mute.MuteID + " " + mute.MuteName + " |\n");
i++;
}
if (invString != "")
invString = invString.Remove(invString.Length - 3, 3);
fileData = Utils.StringToBytes(invString);
IXfer xfer = client.Scene.RequestModuleInterface<IXfer>();
if (xfer != null)
{
xfer.AddNewFile(filename, fileData);
client.SendMuteListUpdate(filename);
}
}
/// <summary>
/// Update the mute (from the client)
/// </summary>
/// <param name = "client"></param>
/// <param name = "MuteID"></param>
/// <param name = "Name"></param>
/// <param name = "Flags"></param>
/// <param name = "AgentID"></param>
private void OnMuteListUpdate(IClientAPI client, UUID MuteID, string Name, int Flags, UUID AgentID)
{
if (!m_useMuteListModule)
return;
UpdateMuteList(MuteID, Name, Flags, client.AgentId);
OnMuteListRequest(client, 0);
}
/// <summary>
/// Remove the mute (from the client)
/// </summary>
/// <param name = "client"></param>
/// <param name = "MuteID"></param>
/// <param name = "Name"></param>
/// <param name = "AgentID"></param>
private void OnMuteListRemove(IClientAPI client, UUID MuteID, string Name, UUID AgentID)
{
if (!m_useMuteListModule)
return;
RemoveMute(MuteID, Name, client.AgentId);
OnMuteListRequest(client, 0);
}
/// <summary>
/// Set up the CAPS for friend conferencing
/// </summary>
/// <param name = "agentID"></param>
/// <param name = "caps"></param>
public OSDMap RegisterCaps(UUID agentID, IHttpServer server)
{
OSDMap retVal = new OSDMap();
retVal["ChatSessionRequest"] = CapsUtil.CreateCAPS("ChatSessionRequest", "");
server.AddStreamHandler(new GenericStreamHandler("POST", retVal["ChatSessionRequest"],
delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ProcessChatSessionRequest(request, agentID);
}));
return retVal;
}
private byte[] ProcessChatSessionRequest(Stream request, UUID Agent)
{
OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml(request);
return Encoding.UTF8.GetBytes(findScene(Agent).EventManager.TriggerChatSessionRequest(Agent, rm));
}
private string OnChatSessionRequest(UUID Agent, OSDMap rm)
{
string method = rm["method"].AsString();
UUID sessionid = UUID.Parse(rm["session-id"].AsString());
IScenePresence SP = findScenePresence(Agent);
IEventQueueService eq = SP.Scene.RequestModuleInterface<IEventQueueService>();
if (method == "start conference")
{
//Create the session.
CreateSession(new ChatSession
{
Members = new List<ChatSessionMember>(),
SessionID = sessionid,
Name = SP.Name + " Conference"
});
OSDArray parameters = (OSDArray) rm["params"];
//Add other invited members.
foreach (OSD param in parameters)
{
AddDefaultPermsMemberToSession(param.AsUUID(), sessionid);
}
//Add us to the session!
AddMemberToGroup(new ChatSessionMember
{
AvatarKey = Agent,
CanVoiceChat = true,
IsModerator = true,
MuteText = false,
MuteVoice = false,
HasBeenAdded = true
}, sessionid);
//Inform us about our room
ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
{
AgentID = Agent,
CanVoiceChat = true,
IsModerator = true,
MuteText = false,
MuteVoice = false,
Transition = "ENTER"
};
eq.ChatterBoxSessionAgentListUpdates(sessionid, new[] {block}, Agent, "ENTER",
findScene(Agent).RegionInfo.RegionHandle);
ChatterBoxSessionStartReplyMessage cs = new ChatterBoxSessionStartReplyMessage
{
VoiceEnabled = true,
TempSessionID = UUID.Random(),
Type = 1,
Success = true,
SessionID = sessionid,
SessionName = SP.Name + " Conference",
ModeratedVoice = true
};
return cs.Serialize().ToString();
}
else if (method == "accept invitation")
{
//They would like added to the group conversation
List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> Us =
new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>();
List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> NotUsAgents =
new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>();
ChatSession session = GetSession(sessionid);
if (session != null)
{
ChatSessionMember thismember = FindMember(sessionid, Agent);
//Tell all the other members about the incoming member
foreach (ChatSessionMember sessionMember in session.Members)
{
ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
{
AgentID = sessionMember.AvatarKey,
CanVoiceChat = sessionMember.CanVoiceChat,
IsModerator = sessionMember.IsModerator,
MuteText = sessionMember.MuteText,
MuteVoice = sessionMember.MuteVoice,
Transition = "ENTER"
};
if (sessionMember.AvatarKey == thismember.AvatarKey)
Us.Add(block);
else
{
if (sessionMember.HasBeenAdded)
// Don't add not joined yet agents. They don't want to be here.
NotUsAgents.Add(block);
}
}
thismember.HasBeenAdded = true;
foreach (ChatSessionMember member in session.Members)
{
eq.ChatterBoxSessionAgentListUpdates(session.SessionID,
member.AvatarKey == thismember.AvatarKey
? NotUsAgents.ToArray()
: Us.ToArray(),
member.AvatarKey, "ENTER",
findScene(Agent).RegionInfo.RegionHandle);
}
return "Accepted";
}
else
return ""; //not this type of session
}
else if (method == "mute update")
{
//Check if the user is a moderator
if (!CheckModeratorPermission(Agent, sessionid))
{
return "";
}
OSDMap parameters = (OSDMap) rm["params"];
UUID AgentID = parameters["agent_id"].AsUUID();
OSDMap muteInfoMap = (OSDMap) parameters["mute_info"];
ChatSessionMember thismember = FindMember(sessionid, AgentID);
if (muteInfoMap.ContainsKey("text"))
thismember.MuteText = muteInfoMap["text"].AsBoolean();
if (muteInfoMap.ContainsKey("voice"))
thismember.MuteVoice = muteInfoMap["voice"].AsBoolean();
ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
{
AgentID = thismember.AvatarKey,
CanVoiceChat = thismember.CanVoiceChat,
IsModerator = thismember.IsModerator,
MuteText = thismember.MuteText,
MuteVoice = thismember.MuteVoice,
Transition = "ENTER"
};
// Send an update to the affected user
eq.ChatterBoxSessionAgentListUpdates(sessionid, new[] {block}, AgentID, "",
findScene(Agent).RegionInfo.RegionHandle);
return "Accepted";
}
else
{
MainConsole.Instance.Warn("ChatSessionRequest : " + method);
return "";
}
}
private IScene findScene(UUID agentID)
{
return (from scene in m_scenes let SP = scene.GetScenePresence(agentID) where SP != null && !SP.IsChildAgent select scene).FirstOrDefault();
}
/// <summary>
/// Find the presence from all the known sims
/// </summary>
/// <param name = "avID"></param>
/// <returns></returns>
public IScenePresence findScenePresence(UUID avID)
{
#if (!ISWIN)
foreach (IScene s in m_scenes)
{
IScenePresence SP = s.GetScenePresence(avID);
if (SP != null)
{
return SP;
}
}
return null;
#else
return m_scenes.Select(s => s.GetScenePresence(avID)).FirstOrDefault(SP => SP != null);
#endif
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
OnInstantMessage(findScenePresence(msg.toAgentID).ControllingClient, msg);
}
/// <summary>
/// If its a message we deal with, pull it from the client here
/// </summary>
/// <param name = "client"></param>
/// <param name = "im"></param>
public void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
byte dialog = im.dialog;
//We only deal with friend IM sessions here, groups module handles group IM sessions
if (dialog == (byte) InstantMessageDialog.SessionSend)
SendChatToSession(client, im);
if (dialog == (byte) InstantMessageDialog.SessionDrop)
DropMemberFromSession(client, im);
}
/// <summary>
/// Find the member from X sessionID
/// </summary>
/// <param name = "sessionid"></param>
/// <param name = "Agent"></param>
/// <returns></returns>
private ChatSessionMember FindMember(UUID sessionid, UUID Agent)
{
ChatSession session;
ChatSessions.TryGetValue(sessionid, out session);
if (session == null)
return null;
ChatSessionMember thismember = new ChatSessionMember {AvatarKey = UUID.Zero};
#if (!ISWIN)
foreach (ChatSessionMember testmember in session.Members)
{
if (testmember.AvatarKey == Agent)
{
thismember = testmember;
}
}
#else
foreach (ChatSessionMember testmember in session.Members.Where(testmember => testmember.AvatarKey == Agent))
{
thismember = testmember;
}
#endif
return thismember;
}
/// <summary>
/// Check whether the user has moderator permissions
/// </summary>
/// <param name = "Agent"></param>
/// <param name = "sessionid"></param>
/// <returns></returns>
public bool CheckModeratorPermission(UUID Agent, UUID sessionid)
{
ChatSession session;
ChatSessions.TryGetValue(sessionid, out session);
if (session == null)
return false;
ChatSessionMember thismember = new ChatSessionMember {AvatarKey = UUID.Zero};
#if (!ISWIN)
foreach (ChatSessionMember testmember in session.Members)
{
if (testmember.AvatarKey == Agent)
{
thismember = testmember;
}
}
#else
foreach (ChatSessionMember testmember in session.Members.Where(testmember => testmember.AvatarKey == Agent))
{
thismember = testmember;
}
#endif
if (thismember == null)
return false;
return thismember.IsModerator;
}
/// <summary>
/// Remove the member from this session
/// </summary>
/// <param name = "client"></param>
/// <param name = "im"></param>
public void DropMemberFromSession(IClientAPI client, GridInstantMessage im)
{
ChatSession session;
ChatSessions.TryGetValue(im.imSessionID, out session);
if (session == null)
return;
ChatSessionMember member = new ChatSessionMember {AvatarKey = UUID.Zero};
#if (!ISWIN)
foreach (ChatSessionMember testmember in session.Members)
{
if (testmember.AvatarKey == im.fromAgentID)
{
member = testmember;
}
}
#else
foreach (ChatSessionMember testmember in session.Members.Where(testmember => testmember.AvatarKey == im.fromAgentID))
{
member = testmember;
}
#endif
if (member.AvatarKey != UUID.Zero)
session.Members.Remove(member);
if (session.Members.Count == 0)
{
ChatSessions.Remove(session.SessionID);
return;
}
ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
{
AgentID = member.AvatarKey,
CanVoiceChat = member.CanVoiceChat,
IsModerator = member.IsModerator,
MuteText = member.MuteText,
MuteVoice = member.MuteVoice,
Transition = "LEAVE"
};
IEventQueueService eq = client.Scene.RequestModuleInterface<IEventQueueService>();
foreach (ChatSessionMember sessionMember in session.Members)
{
eq.ChatterBoxSessionAgentListUpdates(session.SessionID, new[] {block}, sessionMember.AvatarKey, "LEAVE",
findScene(sessionMember.AvatarKey).RegionInfo.RegionHandle);
}
}
/// <summary>
/// Send chat to all the members of this friend conference
/// </summary>
/// <param name = "client"></param>
/// <param name = "im"></param>
public void SendChatToSession(IClientAPI client, GridInstantMessage im)
{
ChatSession session;
ChatSessions.TryGetValue(im.imSessionID, out session);
if (session == null)
return;
IEventQueueService eq = client.Scene.RequestModuleInterface<IEventQueueService>();
foreach (ChatSessionMember member in session.Members)
{
if (member.HasBeenAdded)
{
im.toAgentID = member.AvatarKey;
im.binaryBucket = Utils.StringToBytes(session.Name);
im.RegionID = UUID.Zero;
im.ParentEstateID = 0;
//im.timestamp = 0;
m_TransferModule.SendInstantMessage(im);
}
else
{
im.toAgentID = member.AvatarKey;
eq.ChatterboxInvitation(
session.SessionID
, session.Name
, im.fromAgentID
, im.message
, im.toAgentID
, im.fromAgentName
, im.dialog
, im.timestamp
, im.offline == 1
, (int) im.ParentEstateID
, im.Position
, 1
, im.imSessionID
, false
, Utils.StringToBytes(session.Name)
, findScene(member.AvatarKey).RegionInfo.RegionHandle
);
}
}
}
/// <summary>
/// Add this member to the friend conference
/// </summary>
/// <param name = "member"></param>
/// <param name = "SessionID"></param>
public void AddMemberToGroup(ChatSessionMember member, UUID SessionID)
{
ChatSession session;
ChatSessions.TryGetValue(SessionID, out session);
session.Members.Add(member);
}
/// <summary>
/// Create a new friend conference session
/// </summary>
/// <param name = "session"></param>
public void CreateSession(ChatSession session)
{
ChatSessions.Add(session.SessionID, session);
}
/// <summary>
/// Get a session by a user's sessionID
/// </summary>
/// <param name = "SessionID"></param>
/// <returns></returns>
public ChatSession GetSession(UUID SessionID)
{
ChatSession session;
ChatSessions.TryGetValue(SessionID, out session);
return session;
}
/// <summary>
/// Add the agent to the in-memory session lists and give them the default permissions
/// </summary>
/// <param name = "AgentID"></param>
/// <param name = "SessionID"></param>
private void AddDefaultPermsMemberToSession(UUID AgentID, UUID SessionID)
{
ChatSession session;
ChatSessions.TryGetValue(SessionID, out session);
ChatSessionMember member = new ChatSessionMember
{
AvatarKey = AgentID,
CanVoiceChat = true,
IsModerator = false,
MuteText = false,
MuteVoice = false,
HasBeenAdded = false
};
session.Members.Add(member);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Common;
using NUnit.Framework;
/// <summary>
/// Ignite start/stop tests.
/// </summary>
[Category(TestUtils.CategoryIntensive)]
public class IgniteStartStopTest
{
/// <summary>
/// Test teardown.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[Test]
public void TestStartDefault()
{
var cfg = new IgniteConfiguration {JvmClasspath = TestUtils.CreateTestClasspath()};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.AreEqual(1, grid.GetCluster().GetNodes().Count, "Unexpected number of nodes in the cluster.");
}
/// <summary>
///
/// </summary>
[Test]
public void TestStartWithConfigPath()
{
var cfg = new IgniteConfiguration
{
SpringConfigUrl = Path.Combine("Config", "spring-test.xml"),
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.AreEqual(1, grid.GetCluster().GetNodes().Count);
}
/// <summary>
///
/// </summary>
[Test]
public void TestStartGetStop()
{
var grid1 = Ignition.Start(TestUtils.GetTestConfiguration(name: "grid1"));
Assert.AreEqual("grid1", grid1.Name);
Assert.AreSame(grid1, Ignition.GetIgnite());
Assert.AreSame(grid1, Ignition.GetAll().Single());
var grid2 = Ignition.Start(TestUtils.GetTestConfiguration(name: "grid2"));
Assert.AreEqual("grid2", grid2.Name);
Assert.Throws<IgniteException>(() => Ignition.GetIgnite());
var grid3 = Ignition.Start(TestUtils.GetTestConfiguration());
Assert.IsNull(grid3.Name);
Assert.AreSame(grid1, Ignition.GetIgnite("grid1"));
Assert.AreSame(grid1, Ignition.TryGetIgnite("grid1"));
Assert.AreSame(grid2, Ignition.GetIgnite("grid2"));
Assert.AreSame(grid2, Ignition.TryGetIgnite("grid2"));
Assert.AreSame(grid3, Ignition.GetIgnite(null));
Assert.AreSame(grid3, Ignition.GetIgnite());
Assert.AreSame(grid3, Ignition.TryGetIgnite(null));
Assert.AreSame(grid3, Ignition.TryGetIgnite());
Assert.AreEqual(new[] {grid3, grid1, grid2}, Ignition.GetAll().OrderBy(x => x.Name).ToArray());
Assert.Throws<IgniteException>(() => Ignition.GetIgnite("invalid_name"));
Assert.IsNull(Ignition.TryGetIgnite("invalid_name"));
Assert.IsTrue(Ignition.Stop("grid1", true));
Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid1"));
grid2.Dispose();
Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid2"));
grid3.Dispose();
Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid3"));
// Restart.
Ignition.Start(TestUtils.GetTestConfiguration(name: "grid1"));
Ignition.Start(TestUtils.GetTestConfiguration(name: "grid2"));
Ignition.Start(TestUtils.GetTestConfiguration());
foreach (var gridName in new [] { "grid1", "grid2", null })
Assert.IsNotNull(Ignition.GetIgnite(gridName));
Ignition.StopAll(true);
foreach (var gridName in new [] {"grid1", "grid2", null})
Assert.Throws<IgniteException>(() => Ignition.GetIgnite(gridName));
}
/// <summary>
///
/// </summary>
[Test]
public void TestStartTheSameName()
{
var cfg = TestUtils.GetTestConfiguration(name: "grid1");
var grid1 = Ignition.Start(cfg);
Assert.AreEqual("grid1", grid1.Name);
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
Assert.AreEqual("Ignite instance with this name has already been started: grid1", ex.Message);
}
/// <summary>
/// Tests automatic grid name generation.
/// </summary>
[Test]
public void TestStartUniqueName()
{
var cfg = TestUtils.GetTestConfiguration();
cfg.AutoGenerateIgniteInstanceName = true;
Ignition.Start(cfg);
Assert.IsNotNull(Ignition.GetIgnite());
Assert.IsNotNull(Ignition.TryGetIgnite());
Ignition.Start(cfg);
Assert.Throws<IgniteException>(() => Ignition.GetIgnite());
Assert.IsNull(Ignition.TryGetIgnite());
Assert.AreEqual(2, Ignition.GetAll().Count);
}
/// <summary>
///
/// </summary>
[Test]
public void TestUsageAfterStop()
{
var grid = Ignition.Start(TestUtils.GetTestConfiguration());
Assert.IsNotNull(grid.GetOrCreateCache<int, int>("cache1"));
grid.Dispose();
var ex = Assert.Throws<IgniteIllegalStateException>(() => grid.GetCache<int, int>("cache1"));
Assert.AreEqual("Grid is in invalid state to perform this operation. " +
"It either not started yet or has already being or have stopped " +
"[igniteInstanceName=null, state=STOPPED]", ex.Message);
}
/// <summary>
///
/// </summary>
[Test]
public void TestStartStopLeak()
{
var cfg = TestUtils.GetTestConfiguration();
for (var i = 0; i < 50; i++)
{
Console.WriteLine("Iteration: " + i);
var grid = Ignition.Start(cfg);
UseIgnite(grid);
if (i % 2 == 0) // Try to stop ignite from another thread.
{
TaskRunner.Run(() => grid.Dispose()).Wait();
}
else
{
grid.Dispose();
}
GC.Collect(); // At the time of writing java references are cleaned from finalizer, so GC is needed.
}
}
/// <summary>
/// Tests the client mode flag.
/// </summary>
[Test]
public void TestClientMode()
{
var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "serv"));
var clientCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "client"));
try
{
using (var serv = Ignition.Start(servCfg)) // start server-mode ignite first
{
Assert.IsFalse(serv.GetCluster().GetLocalNode().IsClient);
Ignition.ClientMode = true;
using (var grid = Ignition.Start(clientCfg))
{
Assert.IsTrue(grid.GetCluster().GetLocalNode().IsClient);
UseIgnite(grid);
}
}
}
finally
{
Ignition.ClientMode = false;
}
}
/// <summary>
/// Uses the ignite.
/// </summary>
/// <param name="ignite">The ignite.</param>
private static void UseIgnite(IIgnite ignite)
{
// Create objects holding references to java objects.
var comp = ignite.GetCompute();
// ReSharper disable once RedundantAssignment
comp = comp.WithKeepBinary();
var prj = ignite.GetCluster().ForOldest();
Assert.IsTrue(prj.GetNodes().Count > 0);
Assert.IsNotNull(prj.GetCompute());
var cache = ignite.GetOrCreateCache<int, int>("cache1");
Assert.IsNotNull(cache);
cache.GetAndPut(1, 1);
Assert.AreEqual(1, cache.Get(1));
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using a <see cref="ConstituentsUniverse"/> with test data
/// </summary>
public class ConstituentsUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private readonly Symbol _appl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
private readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
private readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA);
private readonly Symbol _fb = QuantConnect.Symbol.Create("FB", SecurityType.Equity, Market.USA);
private int _step;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
UniverseSettings.Resolution = Resolution.Daily;
var customUniverseSymbol = new Symbol(SecurityIdentifier.GenerateConstituentIdentifier(
"constituents-universe-qctest",
SecurityType.Equity,
Market.USA),
"constituents-universe-qctest");
AddUniverse(new ConstituentsUniverse(customUniverseSymbol, UniverseSettings));
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
_step++;
if (_step == 1)
{
if (!data.ContainsKey(_qqq)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL will be deselected by the ConstituentsUniverse
// but it shouldn't be removed since we hold it
SetHoldings(_appl, 0.5);
}
else if (_step == 2)
{
if (!data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 1)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL should now be released
// note: takes one extra loop because the order is executed on market open
Liquidate();
}
else if (_step == 3)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 3)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 4)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 5)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
}
public override void OnEndOfAlgorithm()
{
if (_step != 5)
{
throw new Exception($"Unexpected step count: {_step}");
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var added in changes.AddedSecurities)
{
Log($"AddedSecurities {added}");
}
foreach (var removed in changes.RemovedSecurities)
{
Log($"RemovedSecurities {removed} {_step}");
// we are currently notifying the removal of AAPl twice,
// when deselected and when finally removed (since it stayed pending)
if (removed.Symbol == _appl && _step != 1 && _step != 2
|| removed.Symbol == _qqq && _step != 1)
{
throw new Exception($"Unexpected removal step count: {_step}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.54%"},
{"Compounding Annual Return", "-32.671%"},
{"Drawdown", "0.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.540%"},
{"Sharpe Ratio", "-3.168"},
{"Probabilistic Sharpe Ratio", "23.963%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.456"},
{"Beta", "0.157"},
{"Annual Standard Deviation", "0.075"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-9.176"},
{"Tracking Error", "0.178"},
{"Treynor Ratio", "-1.514"},
{"Total Fees", "$32.32"},
{"Estimated Strategy Capacity", "$95000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-36.199"},
{"Portfolio Turnover", "0.2"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "3b9c93151bf191a82529e6e915961356"}
};
}
}
| |
//
// MonoTests.System.Diagnostics.StackFrameTest.cs
//
// Author:
// Alexander Klyubin ([email protected])
//
// (C) 2001
//
using System;
using System.Diagnostics;
using System.Reflection;
using NUnit.Framework;
namespace MonoTests.System.Diagnostics {
/// <summary>
/// Tests the case where StackFrame is created for specified file name and
/// location inside it.
/// </summary>
[TestFixture]
public class StackFrameTest1 : Assertion {
private StackFrame frame1;
private StackFrame frame2;
[SetUp]
public void SetUp () {
frame1 = new StackFrame("dir/someFile", 13, 45);
frame2 = new StackFrame("SomeFile2.cs", 24);
}
[TearDown]
public void TearDown () {
frame1 = null;
frame2 = null;
}
/// <summary>
/// Tests whether getting file name works.
/// </summary>
public void TestGetFileName() {
AssertEquals("File name (1)",
"dir/someFile",
frame1.GetFileName());
AssertEquals("File name (2)",
"SomeFile2.cs",
frame2.GetFileName());
}
/// <summary>
/// Tests whether getting file line number works.
/// </summary>
public void TestGetFileLineNumber() {
AssertEquals("Line number (1)",
13,
frame1.GetFileLineNumber());
AssertEquals("Line number (2)",
24,
frame2.GetFileLineNumber());
}
/// <summary>
/// Tests whether getting file column number works.
/// </summary>
public void TestGetFileColumnNumber() {
AssertEquals("Column number (1)",
45,
frame1.GetFileColumnNumber());
AssertEquals("Column number (2)",
0,
frame2.GetFileColumnNumber());
}
/// <summary>
/// Tests whether getting method associated with frame works.
/// </summary>
public void TestGetMethod() {
Assert("Method not null (1)", (frame1.GetMethod() != null));
AssertEquals("Class declaring the method (1)",
this.GetType(),
frame1.GetMethod().DeclaringType);
AssertEquals("Method name (1)",
"SetUp",
frame1.GetMethod().Name);
Assert("Method not null (2)", (frame2.GetMethod() != null));
AssertEquals("Class declaring the method (2)",
this.GetType(),
frame2.GetMethod().DeclaringType);
AssertEquals("Method name (2)",
"SetUp",
frame2.GetMethod().Name);
}
}
/// <summary>
/// Tests the case where StackFrame is created for current method.
/// </summary>
/// <remarks>
/// FIXME: Must be compiled with /debug switch. Otherwise some file
/// information will be incorrect for the following test cases.
/// What's the best way to do both types of tests with and without
/// debug information?
/// </remarks>
[TestFixture]
public class StackFrameTest2 : Assertion {
private StackFrame frame1;
private StackFrame frame2;
private StackFrame frame3;
[SetUp]
public void SetUp() {
frame1 = new StackFrame();
frame2 = new StackFrame(true);
frame3 = new StackFrame(0);
}
[TearDown]
public void TearDown () {
frame1 = null;
frame2 = null;
frame3 = null;
}
/// <summary>
/// Tests whether getting file name works.
/// </summary>
public void TestGetFileName1() {
AssertNull("File name (1)",
frame1.GetFileName());
}
[Ignore("Does not pass on .NET because of AppDomain/StackFrame usage")]
public void TestGetFileName2() {
AssertNotNull("File name not null", frame2.GetFileName());
Assert("File name not empty", frame2.GetFileName().Length == 0);
Assert("File name (2) " + frame2.GetFileName()
+ " ends with StackFrameTest.cs",
frame2.GetFileName().EndsWith("StackFrameTest.cs"));
}
/// <summary>
/// Tests whether getting file line number works.
/// </summary>
[Ignore ("Bug 45730 - Incorrect line numbers returned")]
public void TestGetFileLineNumber() {
AssertEquals("Line number (1)",
0,
frame1.GetFileLineNumber());
AssertEquals("Line number (2)",
119,
frame2.GetFileLineNumber());
AssertEquals("Line number (3)",
0,
frame3.GetFileLineNumber());
}
/// <summary>
/// Tests whether getting file column number works.
/// </summary>
[Ignore ("Bug 45730 - Column numbers always zero")]
public void TestGetFileColumnNumber() {
AssertEquals("Column number (1)",
0,
frame1.GetFileColumnNumber());
AssertEquals("Column number (2)",
25,
frame2.GetFileColumnNumber());
AssertEquals("Column number (3)",
0,
frame3.GetFileColumnNumber());
}
/// <summary>
/// Tests whether getting method associated with frame works.
/// </summary>
public void TestGetMethod() {
Assert("Method not null (1)",
(frame1.GetMethod() != null));
AssertEquals("Class declaring the method (1)",
this.GetType(),
frame1.GetMethod().DeclaringType);
AssertEquals("Method name (1)",
"SetUp",
frame1.GetMethod().Name);
Assert("Method not null (2)",
(frame2.GetMethod() != null));
AssertEquals("Class declaring the method (2)",
this.GetType(),
frame2.GetMethod().DeclaringType);
AssertEquals("Method name (2)",
"SetUp",
frame2.GetMethod().Name);
Assert("Method not null (3)",
(frame3.GetMethod() != null));
AssertEquals("Class declaring the method (3)",
this.GetType(),
frame3.GetMethod().DeclaringType);
AssertEquals("Method name (3)",
"SetUp",
frame3.GetMethod().Name);
}
}
/// <summary>
/// Tests the case where StackFrame is created for current method but
/// skipping some frames.
/// </summary>
/// <remarks>
/// FIXME: Must be compiled with /debug switch. Otherwise some file
/// information will be incorrect for the following test cases.
/// What's the best way to do both types of tests with and without
/// debug information?
/// </remarks>
[TestFixture]
public class StackFrameTest3 : Assertion {
protected StackFrame frame1;
protected StackFrame frame2;
[SetUp]
public void SetUp() {
// In order to get better test cases with stack traces
NestedSetUp();
}
private void NestedSetUp() {
frame1 = new StackFrame(2);
frame2 = new StackFrame(1, true);
// Without this access of frame2 on the RHS, none of
// the properties or methods seem to return any data ???
string s = frame2.GetFileName();
}
[TearDown]
public void TearDown() {
frame1 = null;
frame2 = null;
}
/// <summary>
/// Tests whether getting file name works.
/// </summary>
[Ignore("Does not pass on .NET because of AppDomain/StackFrame usage")]
public void TestGetFileName() {
AssertNull("File name (1)",
frame1.GetFileName());
AssertNotNull("File name (2) should not be null",
frame2.GetFileName());
Assert("File name (2) " + frame2.GetFileName()
+ " ends with StackFrameTest.cs",
frame2.GetFileName().EndsWith("StackFrameTest.cs"));
}
/// <summary>
/// Tests whether getting file line number works.
/// </summary>
[Ignore ("Bug 45730 - Incorrect line numbers returned")]
public void TestGetFileLineNumber() {
AssertEquals("Line number (1)",
0,
frame1.GetFileLineNumber());
AssertEquals("Line number (2)",
236,
frame2.GetFileLineNumber());
}
/// <summary>
/// Tests whether getting file column number works.
/// </summary>
[Ignore ("Bug 45730 - Column numbers always zero")]
public void TestGetFileColumnNumber() {
AssertEquals("Column number (1)",
0,
frame1.GetFileColumnNumber());
AssertEquals("Column number (2)",
17,
frame2.GetFileColumnNumber());
}
/// <summary>
/// Tests whether getting method associated with frame works.
/// </summary>
public void TestGetMethod() {
Assert("Method not null (1)", (frame1.GetMethod() != null));
Assert("Method not null (2)", (frame2.GetMethod() != null));
AssertEquals("Class declaring the method (2)",
this.GetType(),
frame2.GetMethod().DeclaringType);
AssertEquals("Method name (2)",
"SetUp",
frame2.GetMethod().Name);
}
}
}
| |
/*
** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace SharpLua
{
using TValue = Lua.lua_TValue;
using StkId = Lua.lua_TValue;
using lu_byte = System.Byte;
using lua_Number = System.Double;
using l_uacNumber = System.Double;
using Instruction = System.UInt32;
public partial class Lua
{
/* tags for values visible from Lua */
public const int LAST_TAG = LUA_TTHREAD;
public const int NUM_TAGS = (LAST_TAG + 1);
/*
** Extra tags for non-values
*/
public const int LUA_TPROTO = (LAST_TAG + 1);
public const int LUA_TUPVAL = (LAST_TAG + 2);
public const int LUA_TDEADKEY = (LAST_TAG + 3);
public interface ArrayElement
{
void set_index(int index);
void set_array(object array);
}
/*
** Common Header for all collectable objects (in macro form, to be
** included in other objects)
*/
public class CommonHeader
{
public GCObject next;
public lu_byte tt;
public lu_byte marked;
}
/*
** Common header in struct form
*/
public class GCheader : CommonHeader
{
};
/*
** Union of all Lua values (in c# we use virtual data members and boxing)
*/
public class Value
{
// in the original code Value is a struct, so all assignments in the code
// need to be replaced with a call to Copy. as it turns out, there are only
// a couple. the vast majority of references to Value are the instance that
// appears in the TValue class, so if you make that a virtual data member and
// omit the set accessor then you'll get a compiler error if anything tries
// to set it.
public void Copy(Value copy)
{
this.p = copy.p;
}
public GCObject gc
{
get { return (GCObject)this.p; }
set { this.p = value; }
}
public object p;
public lua_Number n
{
get { return (lua_Number)this.p; }
set { this.p = (object)value; }
}
public int b
{
get { return (int)this.p; }
set { this.p = (object)value; }
}
};
/*
** Tagged Values
*/
//#define TValuefields Value value; int tt
public class lua_TValue : ArrayElement
{
private lua_TValue[] values = null;
private int index = -1;
public void set_index(int index)
{
this.index = index;
}
public void set_array(object array)
{
this.values = (lua_TValue[])array;
Debug.Assert(this.values != null);
}
public lua_TValue this[int offset]
{
get { return this.values[this.index + offset]; }
set { this.values[this.index + offset] = value; }
}
public lua_TValue this[uint offset]
{
get { return this.values[this.index + (int)offset]; }
set { this.values[this.index + (int)offset] = value; }
}
public static lua_TValue operator +(lua_TValue value, int offset)
{
return value.values[value.index + offset];
}
public static lua_TValue operator +(int offset, lua_TValue value)
{
return value.values[value.index + offset];
}
public static lua_TValue operator -(lua_TValue value, int offset)
{
return value.values[value.index - offset];
}
public static int operator -(lua_TValue value, lua_TValue[] array)
{
Debug.Assert(value.values == array);
return value.index;
}
public static int operator -(lua_TValue a, lua_TValue b)
{
Debug.Assert(a.values == b.values);
return a.index - b.index;
}
public static bool operator <(lua_TValue a, lua_TValue b)
{
//Console.WriteLine(a.values.Length + " " + b.values.Length);
Debug.Assert(a.values == b.values);
return a.index < b.index;
}
public static bool operator <=(lua_TValue a, lua_TValue b)
{
Debug.Assert(a.values == b.values);
return a.index <= b.index;
}
public static bool operator >(lua_TValue a, lua_TValue b)
{
Debug.Assert(a.values == b.values);
return a.index > b.index;
}
public static bool operator >=(lua_TValue a, lua_TValue b)
{
Debug.Assert(a.values == b.values);
return a.index >= b.index;
}
public static lua_TValue inc(ref lua_TValue value)
{
value = value[1];
return value[-1];
}
public static lua_TValue dec(ref lua_TValue value)
{
value = value[-1];
return value[1];
}
public static implicit operator int(lua_TValue value)
{
return value.index;
}
public lua_TValue()
{
}
public lua_TValue(lua_TValue copy)
{
this.values = copy.values;
this.index = copy.index;
this.value.Copy(copy.value);
this.tt = copy.tt;
}
public lua_TValue(Value value, int tt)
{
this.values = null;
this.index = 0;
this.value.Copy(value);
this.tt = tt;
}
public Value value = new Value();
public int tt;
};
/* Macros to test type */
internal static bool ttisnil(TValue o) { return (ttype(o) == LUA_TNIL); }
internal static bool ttisnumber(TValue o) { return (ttype(o) == LUA_TNUMBER); }
internal static bool ttisstring(TValue o) { return (ttype(o) == LUA_TSTRING); }
internal static bool ttistable(TValue o) { return (ttype(o) == LUA_TTABLE); }
internal static bool ttisfunction(TValue o) { return (ttype(o) == LUA_TFUNCTION); }
internal static bool ttisboolean(TValue o) { return (ttype(o) == LUA_TBOOLEAN); }
internal static bool ttisuserdata(TValue o) { return (ttype(o) == LUA_TUSERDATA); }
internal static bool ttisthread(TValue o) { return (ttype(o) == LUA_TTHREAD); }
internal static bool ttislightuserdata(TValue o) { return (ttype(o) == LUA_TLIGHTUSERDATA); }
/* Macros to access values */
#if DEBUG
public static int ttype(TValue o) { return o.tt; }
public static int ttype(CommonHeader o) { return o.tt; }
public static GCObject gcvalue(TValue o) { return (GCObject)check_exp(iscollectable(o), o.value.gc); }
public static object pvalue(TValue o) { return (object)check_exp(ttislightuserdata(o), o.value.p); }
public static lua_Number nvalue(TValue o) { return (lua_Number)check_exp(ttisnumber(o), o.value.n); }
public static TString rawtsvalue(TValue o) { return (TString)check_exp(ttisstring(o), o.value.gc.ts); }
public static TString_tsv tsvalue(TValue o) { return rawtsvalue(o).tsv; }
public static Udata rawuvalue(TValue o) { return (Udata)check_exp(ttisuserdata(o), o.value.gc.u); }
public static Udata_uv uvalue(TValue o) { return rawuvalue(o).uv; }
public static Closure clvalue(TValue o) { return (Closure)check_exp(ttisfunction(o), o.value.gc.cl); }
public static Table hvalue(TValue o) { return (Table)check_exp(ttistable(o), o.value.gc.h); }
public static int bvalue(TValue o) { return (int)check_exp(ttisboolean(o), o.value.b); }
public static LuaState thvalue(TValue o) { return (LuaState)check_exp(ttisthread(o), o.value.gc.th); }
#else
public static int ttype(TValue o) { return o.tt; }
public static int ttype(CommonHeader o) { return o.tt; }
public static GCObject gcvalue(TValue o) { return o.value.gc; }
public static object pvalue(TValue o) { return o.value.p; }
public static lua_Number nvalue(TValue o) { return o.value.n; }
public static TString rawtsvalue(TValue o) { return o.value.gc.ts; }
public static TString_tsv tsvalue(TValue o) { return rawtsvalue(o).tsv; }
public static Udata rawuvalue(TValue o) { return o.value.gc.u; }
public static Udata_uv uvalue(TValue o) { return rawuvalue(o).uv; }
public static Closure clvalue(TValue o) { return o.value.gc.cl; }
public static Table hvalue(TValue o) { return o.value.gc.h; }
public static int bvalue(TValue o) { return o.value.b; }
public static LuaState thvalue(TValue o) { return (LuaState)check_exp(ttisthread(o), o.value.gc.th); }
#endif
public static int l_isfalse(TValue o) { return ((ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))) ? 1 : 0; }
/*
** for internal debug only
*/
[Conditional("DEBUG")]
internal static void checkconsistency(TValue obj)
{
lua_assert(!iscollectable(obj) || (ttype(obj) == (obj).value.gc.gch.tt));
}
[Conditional("DEBUG")]
internal static void checkliveness(GlobalState g, TValue obj)
{
lua_assert(!iscollectable(obj) ||
((ttype(obj) == obj.value.gc.gch.tt) && !isdead(g, obj.value.gc)));
}
/* Macros to set values */
internal static void setnilvalue(TValue obj)
{
obj.tt = LUA_TNIL;
}
internal static void setnvalue(TValue obj, lua_Number x)
{
obj.value.n = x;
obj.tt = LUA_TNUMBER;
}
internal static void setpvalue(TValue obj, object x)
{
obj.value.p = x;
obj.tt = LUA_TLIGHTUSERDATA;
}
internal static void setbvalue(TValue obj, int x)
{
obj.value.b = x;
obj.tt = LUA_TBOOLEAN;
}
internal static void setsvalue(LuaState L, TValue obj, GCObject x)
{
obj.value.gc = x;
obj.tt = LUA_TSTRING;
checkliveness(G(L), obj);
}
internal static void setuvalue(LuaState L, TValue obj, GCObject x)
{
obj.value.gc = x;
obj.tt = LUA_TUSERDATA;
checkliveness(G(L), obj);
}
internal static void setthvalue(LuaState L, TValue obj, GCObject x)
{
obj.value.gc = x;
obj.tt = LUA_TTHREAD;
checkliveness(G(L), obj);
}
internal static void setclvalue(LuaState L, TValue obj, Closure x)
{
obj.value.gc = x;
obj.tt = LUA_TFUNCTION;
checkliveness(G(L), obj);
}
internal static void sethvalue(LuaState L, TValue obj, Table x)
{
obj.value.gc = x;
obj.tt = LUA_TTABLE;
checkliveness(G(L), obj);
}
internal static void setptvalue(LuaState L, TValue obj, Proto x)
{
obj.value.gc = x;
obj.tt = LUA_TPROTO;
checkliveness(G(L), obj);
}
internal static void setobj(LuaState L, TValue obj1, TValue obj2)
{
obj1.value.Copy(obj2.value);
obj1.tt = obj2.tt;
checkliveness(G(L), obj1);
}
/*
** different types of sets, according to destination
*/
/* from stack to (same) stack */
//#define setobjs2s setobj
public static void setobjs2s(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); }
///* to stack (not from same stack) */
//#define setobj2s setobj
public static void setobj2s(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); }
//#define setsvalue2s setsvalue
public static void setsvalue2s(LuaState L, TValue obj, TString x) { setsvalue(L, obj, x); }
//#define sethvalue2s sethvalue
public static void sethvalue2s(LuaState L, TValue obj, Table x) { sethvalue(L, obj, x); }
//#define setptvalue2s setptvalue
public static void setptvalue2s(LuaState L, TValue obj, Proto x) { setptvalue(L, obj, x); }
///* from table to same table */
//#define setobjt2t setobj
public static void setobjt2t(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); }
///* to table */
//#define setobj2t setobj
public static void setobj2t(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); }
///* to new object */
//#define setobj2n setobj
public static void setobj2n(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); }
//#define setsvalue2n setsvalue
public static void setsvalue2n(LuaState L, TValue obj, TString x) { setsvalue(L, obj, x); }
public static void setttype(TValue obj, int tt) { obj.tt = tt; }
public static bool iscollectable(TValue o) { return (ttype(o) >= LUA_TSTRING); }
//typedef TValue *StkId; /* index to stack elements */
/*
** String headers for string table
*/
public class TString_tsv : GCObject
{
public lu_byte reserved;
public uint hash;
public uint len;
};
public class TString : TString_tsv
{
//public L_Umaxalign dummy; /* ensures maximum alignment for strings */
public TString_tsv tsv { get { return this; } }
public TString()
{
}
public TString(CharPtr str) { this.str = str; }
public CharPtr str;
public override string ToString() { return str.ToString(); } // for debugging
};
public static CharPtr getstr(TString ts) { return ts.str; }
public static CharPtr svalue(StkId o) { return getstr(rawtsvalue(o)); }
public class Udata_uv : GCObject
{
public Table metatable;
public Table env;
public uint len;
};
public class Udata : Udata_uv
{
public Udata() { this.uv = this; }
public new Udata_uv uv;
//public L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
// in the original C code this was allocated alongside the structure memory. it would probably
// be possible to still do that by allocating memory and pinning it down, but we can do the
// same thing just as easily by allocating a seperate byte array for it instead.
public object user_data;
};
/*
** Function Prototypes
*/
public class Proto : GCObject
{
public Proto[] protos = null;
public int index = 0;
public Proto this[int offset] { get { return this.protos[this.index + offset]; } }
public TValue[] k; /* constants used by the function */
//public Instruction[] code;
public uint[] code;
public new Proto[] p; /* functions defined inside the function */
public int[] lineinfo; /* map from opcodes to source lines */
public LocVar[] locvars; /* information about local variables */
public TString[] upvalues; /* upvalue names */
public TString source;
public int sizeupvalues;
public int sizek; /* size of `k' */
public int sizecode;
public int sizelineinfo;
public int sizep; /* size of `p' */
public int sizelocvars;
public int linedefined;
public int lastlinedefined;
public GCObject gclist;
public lu_byte nups; /* number of upvalues */
public lu_byte numparams;
public lu_byte is_vararg;
public lu_byte maxstacksize;
};
/* masks for new-style vararg */
public const int VARARG_HASARG = 1;
public const int VARARG_ISVARARG = 2;
public const int VARARG_NEEDSARG = 4;
public class LocVar
{
public TString varname;
public int startpc; /* first point where variable is active */
public int endpc; /* first point where variable is dead */
};
/*
** Upvalues
*/
public class UpVal : GCObject
{
public TValue v; /* points to stack or to its own value */
public class _u
{
public TValue value = new TValue(); /* the value (when closed) */
public class _l
{ /* double linked list (when open) */
public UpVal prev;
public UpVal next;
};
public _l l = new _l();
}
public new _u u = new _u();
};
/*
** Closures
*/
public class ClosureHeader : GCObject
{
public lu_byte isC;
public lu_byte nupvalues;
public GCObject gclist;
public Table env;
};
public class ClosureType
{
ClosureHeader header;
public static implicit operator ClosureHeader(ClosureType ctype) { return ctype.header; }
public ClosureType(ClosureHeader header) { this.header = header; }
public lu_byte isC { get { return header.isC; } set { header.isC = value; } }
public lu_byte nupvalues { get { return header.nupvalues; } set { header.nupvalues = value; } }
public GCObject gclist { get { return header.gclist; } set { header.gclist = value; } }
public Table env { get { return header.env; } set { header.env = value; } }
}
public class CClosure : ClosureType
{
public CClosure(ClosureHeader header) : base(header) { }
public lua_CFunction f;
public TValue[] upvalue;
};
public class LClosure : ClosureType
{
public LClosure(ClosureHeader header) : base(header) { }
public Proto p;
public UpVal[] upvals;
};
public class Closure : ClosureHeader
{
public Closure()
{
c = new CClosure(this);
l = new LClosure(this);
}
public CClosure c;
public LClosure l;
};
public static bool iscfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC != 0)); }
public static bool isLfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC == 0)); }
/*
** Tables
*/
public class TKey_nk : TValue
{
public TKey_nk() { }
public TKey_nk(Value value, int tt, Node next)
: base(value, tt)
{
this.next = next;
}
public Node next; /* for chaining */
};
public class TKey
{
public TKey()
{
this.nk = new TKey_nk();
}
public TKey(TKey copy)
{
this.nk = new TKey_nk(copy.nk.value, copy.nk.tt, copy.nk.next);
}
public TKey(Value value, int tt, Node next)
{
this.nk = new TKey_nk(value, tt, next);
}
public TKey_nk nk = new TKey_nk();
public TValue tvk { get { return this.nk; } }
};
public class Node : ArrayElement
{
private Node[] values = null;
private int index = -1;
public void set_index(int index)
{
this.index = index;
}
public void set_array(object array)
{
this.values = (Node[])array;
Debug.Assert(this.values != null);
}
public Node()
{
this.i_val = new TValue();
this.i_key = new TKey();
}
public Node(Node copy)
{
this.values = copy.values;
this.index = copy.index;
this.i_val = new TValue(copy.i_val);
this.i_key = new TKey(copy.i_key);
}
public Node(TValue i_val, TKey i_key)
{
this.values = new Node[] { this };
this.index = 0;
this.i_val = i_val;
this.i_key = i_key;
}
public TValue i_val;
public TKey i_key;
public Node this[uint offset]
{
get { return this.values[this.index + (int)offset]; }
}
public Node this[int offset]
{
get { return this.values[this.index + offset]; }
}
public static int operator -(Node n1, Node n2)
{
Debug.Assert(n1.values == n2.values);
return n1.index - n2.index;
}
public static Node inc(ref Node node)
{
node = node[1];
return node[-1];
}
public static Node dec(ref Node node)
{
node = node[-1];
return node[1];
}
public static bool operator >(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index > n2.index; }
public static bool operator >=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index >= n2.index; }
public static bool operator <(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index < n2.index; }
public static bool operator <=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index <= n2.index; }
public static bool operator ==(Node n1, Node n2)
{
object o1 = n1 as Node;
object o2 = n2 as Node;
if ((o1 == null) && (o2 == null)) return true;
if (o1 == null) return false;
if (o2 == null) return false;
if (n1.values != n2.values) return false;
return n1.index == n2.index;
}
public static bool operator !=(Node n1, Node n2) { return !(n1 == n2); }
public override bool Equals(object o) { return this == (Node)o; }
public override int GetHashCode() { return 0; }
};
public class Table : GCObject
{
public lu_byte flags; /* 1<<p means tagmethod(p) is not present */
public lu_byte lsizenode; /* log2 of size of `node' array */
public Table metatable;
public TValue[] array; /* array part */
public Node[] node;
public int lastfree; /* any free position is before this position */
public GCObject gclist;
public int sizearray; /* size of `array' array */
};
/*
** `module' operation for hashing (size is always a power of 2)
*/
//#define lmod(s,size) \
// (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
internal static int twoto(int x) { return 1 << x; }
internal static int sizenode(Table t) { return twoto(t.lsizenode); }
public static TValue luaO_nilobject_ = new TValue(new Value(), LUA_TNIL);
public static TValue luaO_nilobject = luaO_nilobject_;
public static int ceillog2(int x) { return luaO_log2((uint)(x - 1)) + 1; }
/*
** converts an integer to a "floating point byte", represented as
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
** eeeee != 0 and (xxx) otherwise.
*/
public static int luaO_int2fb(uint x)
{
int e = 0; /* expoent */
while (x >= 16)
{
x = (x + 1) >> 1;
e++;
}
if (x < 8) return (int)x;
else return ((e + 1) << 3) | (cast_int(x) - 8);
}
/* converts back */
public static int luaO_fb2int(int x)
{
int e = (x >> 3) & 31;
if (e == 0) return x;
else return ((x & 7) + 8) << (e - 1);
}
private readonly static lu_byte[] log_2 = {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
public static int luaO_log2(uint x)
{
int l = -1;
while (x >= 256) { l += 8; x >>= 8; }
return l + log_2[x];
}
public static int luaO_rawequalObj(TValue t1, TValue t2)
{
if (ttype(t1) != ttype(t2)) return 0;
else switch (ttype(t1))
{
case LUA_TNIL:
return 1;
case LUA_TNUMBER:
return luai_numeq(nvalue(t1), nvalue(t2)) ? 1 : 0;
case LUA_TBOOLEAN:
return bvalue(t1) == bvalue(t2) ? 1 : 0; /* boolean true must be 1....but not in C# !! */
case LUA_TLIGHTUSERDATA:
return pvalue(t1) == pvalue(t2) ? 1 : 0;
default:
lua_assert(iscollectable(t1));
return gcvalue(t1) == gcvalue(t2) ? 1 : 0;
}
}
public static int luaO_str2d(CharPtr s, out lua_Number result)
{
CharPtr endptr;
result = lua_str2number(s, out endptr);
if (endptr == s)
return 0; /* conversion failed */
if (endptr[0] == 'x' || endptr[0] == 'X') /* maybe an hexadecimal constant? */
result = cast_num(strtoul(s, out endptr, 16));
if ((endptr[0] == 'o' || endptr[0] == 'O') && (endptr + 1 != '\0'))
result = cast_num(strtoul(endptr + 1, out endptr, 8));
if ((endptr[0] == 'b' || endptr[0] == 'B') && (endptr + 1 != '\0'))
result = cast_num(strtoul(endptr + 1, out endptr, 2));
if (endptr[0] == '\0')
return 1; /* most common case */
while (isspace(endptr[0]))
endptr = endptr.next();
if (endptr[0] != '\0')
return 0; /* invalid trailing characters? */
return 1;
}
private static void pushstr(LuaState L, CharPtr str)
{
setsvalue2s(L, L.top, luaS_new(L, str));
incr_top(L);
}
/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
public static CharPtr luaO_pushvfstring(LuaState L, CharPtr fmt, params object[] argp)
{
int parm_index = 0;
int n = 1;
pushstr(L, "");
for (; ; )
{
CharPtr e = strchr(fmt, '%');
if (e == null) break;
setsvalue2s(L, L.top, luaS_newlstr(L, fmt, (uint)(e - fmt)));
incr_top(L);
switch (e[1])
{
case 's':
{
object o = argp[parm_index++];
CharPtr s = o as CharPtr;
if (s == null)
s = (string)o;
if (s == null) s = "(null)";
pushstr(L, s);
break;
}
case 'c':
{
CharPtr buff = new char[2];
buff[0] = (char)(int)argp[parm_index++];
buff[1] = '\0';
pushstr(L, buff);
break;
}
case 'd':
{
setnvalue(L.top, (int)argp[parm_index++]);
incr_top(L);
break;
}
case 'f':
{
setnvalue(L.top, (l_uacNumber)argp[parm_index++]);
incr_top(L);
break;
}
case 'p':
{
//CharPtr buff = new char[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
CharPtr buff = new char[32];
sprintf(buff, "0x%08x", argp[parm_index++].GetHashCode());
pushstr(L, buff);
break;
}
case '%':
{
pushstr(L, "%");
break;
}
default:
{
CharPtr buff = new char[3];
buff[0] = '%';
buff[1] = e[1];
buff[2] = '\0';
pushstr(L, buff);
break;
}
}
n += 2;
fmt = e + 2;
}
pushstr(L, fmt);
luaV_concat(L, n + 1, cast_int(L.top - L.base_) - 1);
L.top -= n;
return svalue(L.top - 1);
}
public static CharPtr luaO_pushfstring(LuaState L, CharPtr fmt, params object[] args)
{
return luaO_pushvfstring(L, fmt, args);
}
public static void luaO_chunkid(CharPtr out_, CharPtr source, uint bufflen)
{
//out_ = "";
if (source[0] == '=')
{
strncpy(out_, source + 1, (int)bufflen); /* remove first char */
out_[bufflen - 1] = '\0'; /* ensures null termination */
}
else
{ /* out = "source", or "...source" */
if (source[0] == '@')
{
uint l;
source = source.next(); /* skip the `@' */
bufflen -= (uint)(" '...' ".Length + 1);
l = (uint)strlen(source);
strcpy(out_, "");
if (l > bufflen)
{
source += (l - bufflen); /* get last part of file name */
strcat(out_, "...");
}
strcat(out_, source);
}
else
{ /* out = [string "string"] */
uint len = strcspn(source, "\n\r"); /* stop at first newline */
bufflen -= (uint)(" [string \"...\"] ".Length + 1);
if (len > bufflen) len = bufflen;
strcpy(out_, "[string \"");
if (source[len] != '\0')
{ /* must truncate? */
strncat(out_, source, (int)len); out_ += (int)len;
strcpy(out_, "...");
}
else
strcat(out_, source);
strcat(out_, "\"]");
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class SequenceEqualTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
var q2 = from x2 in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void BothEmpty()
{
int[] first = { };
int[] second = { };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchInMiddle()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 6, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NullComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.False(first.SequenceEqual(second, null));
Assert.False(FlipIsCollection(first).SequenceEqual(second, null));
Assert.False(first.SequenceEqual(FlipIsCollection(second), null));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), null));
}
[Fact]
public void CustomComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.True(first.SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(first.SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
}
[Fact]
public void BothSingleNullExplicitComparer()
{
string[] first = { null };
string[] second = { null };
Assert.True(first.SequenceEqual(second, StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(second, StringComparer.Ordinal));
Assert.True(first.SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
}
[Fact]
public void BothMatchIncludingNullElements()
{
int?[] first = { -6, null, 0, -4, 9, 10, 20 };
int?[] second = { -6, null, 0, -4, 9, 10, 20 };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void EmptyWithNonEmpty()
{
int?[] first = { };
int?[] second = { 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NonEmptyWithEmpty()
{
int?[] first = { 2, 3, 4 };
int?[] second = { };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchingSingletons()
{
int?[] first = { 2 };
int?[] second = { 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnFirst()
{
int?[] first = { 1, 2, 3, 4, 5 };
int?[] second = { 2, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnLast()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void SecondLargerThanFirst()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 3, 4, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstLargerThanSecond()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstSourceNull()
{
int[] first = null;
int[] second = { };
Assert.Throws<ArgumentNullException>("first", () => first.SequenceEqual(second));
}
[Fact]
public void SecondSourceNull()
{
int[] first = { };
int[] second = null;
Assert.Throws<ArgumentNullException>("second", () => first.SequenceEqual(second));
}
}
}
| |
// <copyright file="MetricSnapshotWriterExtensions.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using App.Metrics.Apdex;
using App.Metrics.BucketHistogram;
using App.Metrics.BucketTimer;
using App.Metrics.Counter;
using App.Metrics.Histogram;
using App.Metrics.Meter;
using App.Metrics.Timer;
namespace App.Metrics.Serialization
{
public static class MetricSnapshotWriterExtensions
{
public static void WriteApdex(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<ApdexValue> valueSource,
IDictionary<ApdexFields, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var data = new Dictionary<string, object>();
var value = valueSource.ValueProvider.GetValue(valueSource.ResetOnReporting);
value.AddApdexValues(data, fields);
WriteMetric(writer, context, valueSource, data, timestamp);
}
public static void WriteCounter(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<CounterValue> valueSource,
CounterValueSource counterValueSource,
IDictionary<CounterFields, string> fields,
DateTime timestamp)
{
if (counterValueSource == null || fields.Count == 0)
{
return;
}
var value = counterValueSource.ValueProvider.GetValue(counterValueSource.ResetOnReporting);
if (value.Items.Any() && counterValueSource.ReportSetItems && fields.ContainsKey(CounterFields.SetItem))
{
var itemSuffix = fields[CounterFields.SetItem];
foreach (var item in value.Items.Distinct())
{
var itemData = new Dictionary<string, object>();
if (fields.ContainsKey(CounterFields.Total))
{
itemData.Add(fields[CounterFields.Total], item.Count);
}
if (counterValueSource.ReportItemPercentages && fields.ContainsKey(CounterFields.SetItemPercent))
{
itemData.AddIfNotNanOrInfinity(fields[CounterFields.SetItemPercent], item.Percent);
}
if (itemData.Any())
{
WriteMetricWithSetItems(
writer,
context,
valueSource,
item.Tags,
itemData,
itemSuffix,
timestamp);
}
}
}
if (fields.ContainsKey(CounterFields.Value))
{
var count = value.Count;
WriteMetricValue(writer, context, valueSource, fields[CounterFields.Value], count, timestamp);
}
}
public static void WriteGauge(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<double> valueSource,
IDictionary<GaugeFields, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var value = valueSource.ValueProvider.GetValue(valueSource.ResetOnReporting);
if (!double.IsNaN(value) && !double.IsInfinity(value) && fields.ContainsKey(GaugeFields.Value))
{
WriteMetricValue(writer, context, valueSource, fields[GaugeFields.Value], value, timestamp);
}
}
public static void WriteHistogram(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<HistogramValue> valueSource,
IDictionary<HistogramFields, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var data = new Dictionary<string, object>();
var value = valueSource.ValueProvider.GetValue(valueSource.ResetOnReporting);
value.AddHistogramValues(data, fields);
WriteMetric(writer, context, valueSource, data, timestamp);
}
public static void WriteBucketHistogram(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<BucketHistogramValue> valueSource,
IDictionary<string, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var data = new Dictionary<string, object>();
valueSource.Value.AddBucketHistogramValues(data, fields);
WriteMetric(writer, context, valueSource, data, timestamp);
}
public static void WriteBucketTimer(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<BucketTimerValue> valueSource,
IDictionary<string, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var data = new Dictionary<string, object>();
valueSource.Value.AddBucketTimerValues(data, fields);
WriteMetric(writer, context, valueSource, data, timestamp);
}
public static void WriteMeter(
this IMetricSnapshotWriter writer,
string context,
MeterValueSource valueSource,
IDictionary<MeterFields, string> fields,
DateTime timestamp)
{
if (valueSource == null || fields.Count == 0)
{
return;
}
var data = new Dictionary<string, object>();
var value = valueSource.ValueProvider.GetValue(valueSource.ResetOnReporting);
if (value.Items.Any() && valueSource.ReportSetItems && fields.ContainsKey(MeterFields.SetItem))
{
var itemSuffix = fields[MeterFields.SetItem];
foreach (var item in value.Items.Distinct())
{
var setItemData = new Dictionary<string, object>();
item.AddMeterSetItemValues(setItemData, fields);
if (setItemData.Any())
{
WriteMetricWithSetItems(
writer,
context,
valueSource,
item.Tags,
setItemData,
itemSuffix,
timestamp);
}
}
}
value.AddMeterValues(data, fields);
WriteMetric(writer, context, valueSource, data, timestamp);
}
public static void WriteTimer(
this IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<TimerValue> valueSource,
IDictionary<MeterFields, string> meterFields,
IDictionary<HistogramFields, string> histogramFields,
DateTime timestamp)
{
if (valueSource == null)
{
return;
}
var data = new Dictionary<string, object>();
var value = valueSource.ValueProvider.GetValue(valueSource.ResetOnReporting);
if (meterFields.Count > 0)
{
value.Rate.AddMeterValues(data, meterFields);
}
if (histogramFields.Count > 0)
{
value.Histogram.AddHistogramValues(data, histogramFields);
}
if (data.Count > 0)
{
WriteMetric(writer, context, valueSource, data, timestamp);
}
}
private static MetricTags ConcatIntrinsicMetricTags<T>(MetricValueSourceBase<T> valueSource)
{
var intrinsicTags = new MetricTags(AppMetricsConstants.Pack.MetricTagsUnitKey, valueSource.Unit.ToString());
if (typeof(T) == typeof(TimerValue))
{
var timerValueSource = valueSource as MetricValueSourceBase<TimerValue>;
var timerIntrinsicTags = new MetricTags(
new[] { AppMetricsConstants.Pack.MetricTagsUnitRateDurationKey, AppMetricsConstants.Pack.MetricTagsUnitRateKey },
new[] { timerValueSource?.Value.DurationUnit.Unit(), timerValueSource?.Value.Rate.RateUnit.Unit() });
intrinsicTags = MetricTags.Concat(intrinsicTags, timerIntrinsicTags);
}
else if (typeof(T) == typeof(MeterValue))
{
var meterValueSource = valueSource as MetricValueSourceBase<MeterValue>;
var meterIntrinsicTags = new MetricTags(AppMetricsConstants.Pack.MetricTagsUnitRateKey, meterValueSource?.Value.RateUnit.Unit());
intrinsicTags = MetricTags.Concat(intrinsicTags, meterIntrinsicTags);
}
if (AppMetricsConstants.Pack.MetricValueSourceTypeMapping.ContainsKey(typeof(T)))
{
var metricTypeTag = new MetricTags(AppMetricsConstants.Pack.MetricTagsTypeKey, AppMetricsConstants.Pack.MetricValueSourceTypeMapping[typeof(T)]);
intrinsicTags = MetricTags.Concat(metricTypeTag, intrinsicTags);
}
else
{
var metricTypeTag = new MetricTags(AppMetricsConstants.Pack.MetricTagsTypeKey, typeof(T).Name.ToLowerInvariant());
intrinsicTags = MetricTags.Concat(metricTypeTag, intrinsicTags);
}
return intrinsicTags;
}
private static MetricTags ConcatMetricTags<T>(MetricValueSourceBase<T> valueSource, MetricTags setItemTags)
{
var tagsWithSetItems = MetricTags.Concat(valueSource.Tags, setItemTags);
var intrinsicTags = ConcatIntrinsicMetricTags(valueSource);
return MetricTags.Concat(tagsWithSetItems, intrinsicTags);
}
private static MetricTags ConcatMetricTags<T>(MetricValueSourceBase<T> valueSource)
{
var intrinsicTags = ConcatIntrinsicMetricTags(valueSource);
return MetricTags.Concat(valueSource.Tags, intrinsicTags);
}
private static void WriteMetric<T>(
IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<T> valueSource,
IDictionary<string, object> data,
DateTime timestamp)
{
var keys = data.Keys.ToList();
var values = keys.Select(k => data[k]);
var tags = ConcatMetricTags(valueSource);
if (valueSource.IsMultidimensional)
{
writer.Write(
context,
valueSource.MultidimensionalName,
keys,
values,
tags,
timestamp);
return;
}
writer.Write(context, valueSource.Name, keys, values, tags, timestamp);
}
private static void WriteMetricValue<T>(
IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<T> valueSource,
string field,
object value,
DateTime timestamp)
{
var tags = ConcatMetricTags(valueSource);
if (valueSource.IsMultidimensional)
{
writer.Write(
context,
valueSource.MultidimensionalName,
field,
value,
tags,
timestamp);
return;
}
writer.Write(context, valueSource.Name, field, value, tags, timestamp);
}
private static void WriteMetricWithSetItems<T>(
IMetricSnapshotWriter writer,
string context,
MetricValueSourceBase<T> valueSource,
MetricTags setItemTags,
IDictionary<string, object> itemData,
string metricSetItemSuffix,
DateTime timestamp)
{
var keys = itemData.Keys.ToList();
var values = keys.Select(k => itemData[k]);
var tags = ConcatMetricTags(valueSource, setItemTags);
if (valueSource.IsMultidimensional)
{
writer.Write(
context,
valueSource.MultidimensionalName + metricSetItemSuffix,
keys,
values,
tags,
timestamp);
return;
}
writer.Write(context, valueSource.Name + metricSetItemSuffix, keys, values, tags, timestamp);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.skinning;
using System.Xml;
using System.Text;
using umbraco.interfaces.skinning;
using umbraco.IO;
using umbraco.cms.businesslogic.template;
using umbraco.BusinessLogic;
using umbraco.NodeFactory;
using umbraco.cms.businesslogic.packager;
using System.IO;
using Umbraco.Core;
namespace umbraco.presentation.LiveEditing.Modules.SkinModule
{
public partial class SkinCustomizer : UserControl
{
// Fields
private cms.businesslogic.packager.repositories.Repository repo;
private cms.businesslogic.skinning.Skin ActiveSkin;
private string repoGuid = "65194810-1f85-11dd-bd0b-0800200c9a66";
private List<Dependency> sDependencies = new List<Dependency>();
// Methods
public SkinCustomizer()
{
this.repo = cms.businesslogic.packager.repositories.Repository.getByGuid(this.repoGuid);
}
protected void btnOk_Click(object sender, EventArgs e)
{
this.ActiveSkin.SaveOutput();
//css vars
SortedList<string, string> cssVars = new SortedList<string, string>();
if (this.ActiveSkin.Css != null)
{
foreach (CssVariable cssVar in this.ActiveSkin.Css.Variables)
{
cssVars.Add(cssVar.Name, cssVar.DefaultValue);
}
}
foreach (Dependency dependency in this.sDependencies)
{
if (dependency.DependencyType.Values.Count > 0)
{
string output = dependency.DependencyType.Values[0].ToString();
foreach (Task task in dependency.Tasks)
{
TaskExecutionDetails details = task.TaskType.Execute(this.ParsePlaceHolders(task.Value, output));
if (details.TaskExecutionStatus == TaskExecutionStatus.Completed)
{
this.ActiveSkin.AddTaskHistoryNode(task.TaskType.ToXml(details.OriginalValue, details.NewValue));
}
}
//css vars
if (!string.IsNullOrEmpty(dependency.Variable))
{
if(cssVars[dependency.Variable] != null)
cssVars[dependency.Variable] = output;
}
}
}
if (this.ActiveSkin.Css != null && !string.IsNullOrEmpty(this.ActiveSkin.Css.Content) && !string.IsNullOrEmpty(this.ActiveSkin.Css.TargetFile))
{
string content = this.ActiveSkin.Css.Content;
//css vars
foreach (var var in cssVars)
{
content = content.Replace("@" + var.Key, var.Value);
}
//save
StreamWriter sw = File.AppendText(IO.IOHelper.MapPath(SystemDirectories.Css) + "/" + this.ActiveSkin.Css.TargetFile);
sw.Write(content);
sw.Close();
}
//NOTE: This seems excessive to have to re-load all content from the database here!?
library.RefreshContent();
}
protected void LoadDependencies()
{
this.ph_dependencies.Controls.Clear();
StringBuilder builder = new StringBuilder();
//css vars default value
string varquery = "";
if (this.ActiveSkin.Css != null)
{
foreach (CssVariable cssVar in this.ActiveSkin.Css.Variables)
{
builder.AppendLine(
string.Format("var cssvar{0} = '{1}';",cssVar.Name,cssVar.DefaultValue));
varquery += string.Format("+ '&{0}=' + cssvar{0}.replace('#','%23')", cssVar.Name);
}
}
//preview css var change
builder.Append(string.Format("function PreviewCssVariables(){{ var parsedcsscontent; jQuery.get('/umbraco/LiveEditing/Modules/SkinModule/CssParser.aspx?skinAlias={0}'{1}, function(data){{parsedcsscontent= data; jQuery('head').append('<style>' + parsedcsscontent + '</style>'); }}); }}",
this.ActiveSkin.Alias,
varquery));
builder.Append("\r\n var hasSetTasksClientScriptsRun = false; \r\n function setTasksClientScripts(){ \r\n if(hasSetTasksClientScriptsRun == false){");
int c = 0;
foreach (Dependency dependency in this.ActiveSkin.Dependencies)
{
if (dependency.DependencyType != null)
{
this.sDependencies.Add(dependency);
Control editor = dependency.DependencyType.Editor;
editor.ID = "depcontrol" + c;
this.ph_dependencies.addProperty(dependency.Label, editor);
if(!string.IsNullOrEmpty(dependency.Variable))
{
//this control is setting a css variable
builder.Append(dependency.DependencyType.CssVariablePreviewClientScript(editor.ClientID, "cssvar" + dependency.Variable));
}
foreach (Task task in dependency.Tasks)
{
builder.Append(task.TaskType.PreviewClientScript(editor.ClientID, dependency.DependencyType.ClientSidePreviewEventType(), dependency.DependencyType.ClientSideGetValueScript()));
}
c++;
}
}
builder.Append("hasSetTasksClientScriptsRun = true; }}");
ScriptManager.RegisterClientScriptBlock(this, base.GetType(), "TasksClientScripts", builder.ToString(), true);
}
protected void LoadSkins()
{
List<string> skinNames = new List<string>();
Guid? nullable = Skinning.StarterKitGuid(Node.GetCurrent().template);
if(nullable.HasValue){
InstalledPackage p = InstalledPackage.GetByGuid(nullable.Value.ToString());
if(p.Data.SkinRepoGuid != null && p.Data.SkinRepoGuid != Guid.Empty && p.Data.SkinRepoGuid.ToString() != repoGuid)
this.repo = cms.businesslogic.packager.repositories.Repository.getByGuid(p.Data.SkinRepoGuid.ToString());
}
if (!(nullable.HasValue && Skinning.HasAvailableSkins(Node.GetCurrent().template)))
{
this.pChangeSkin.Visible = false;
}
else if (this.repo.HasConnection())
{
try
{
var skins = this.repo.Webservice.Skins(nullable.ToString());
this.rep_starterKitDesigns.DataSource = skins;
this.rep_starterKitDesigns.DataBind();
foreach (var s in skins)
{
if(!skinNames.Contains(s.Text))
skinNames.Add(s.Text);
}
}
catch (Exception exception)
{
LogHelper.Error<SkinCustomizer>("An error occurred", exception);
}
}
else
{
this.ShowConnectionError();
}
//check for local skins
List<string> localSkins = new List<string>();
DirectoryInfo dirInfo = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Masterpages));
foreach (DirectoryInfo subDur in dirInfo.GetDirectories())
{
var skinFile = subDur.GetFiles("skin.xml");
if (skinFile.Length > 0)
{
string c = Skin.GetSkinNameFromFile(skinFile[0].FullName);
if (!skinNames.Contains(c))
localSkins.Add(c);
}
}
if (localSkins.Count > 0)
{
rep_starterKitDesignsLocal.DataSource = localSkins;
rep_starterKitDesignsLocal.DataBind();
}
else
{
localSkinsContainer.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (User.GetCurrent().GetApplications().Find(t => string.Equals(t.alias, Constants.Applications.Settings, StringComparison.OrdinalIgnoreCase)) == null)
{
throw new Exception("The current user can't edit skins as the user doesn't have access to the Settings section!");
}
NodeFactory.Node n = NodeFactory.Node.GetCurrent();
ActiveSkin = Skin.CreateFromAlias( Skinning.GetCurrentSkinAlias(n.template) );
pnl_connectionerror.Visible = false;
//load dependencies
if (ActiveSkin != null && ActiveSkin.Dependencies.Count > 0)
LoadDependencies();
else
{
//show skin selection
pCustomizeSkin.Visible = false;
ltCustomizeSkinStyle.Text = ltChangeSkinStyle.Text;
ltChangeSkinStyle.Text = string.Empty;
}
LoadSkins();
}
private string ParsePlaceHolders(string value, string output)
{
value = value.Replace("${Output}", output);
return value;
}
protected void rep_starterKitDesigns_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
cms.businesslogic.packager.repositories.Skin s = (cms.businesslogic.packager.repositories.Skin)e.Item.DataItem;
if (Skinning.IsSkinInstalled(s.RepoGuid))
{
Button inst = (Button)e.Item.FindControl("Button1");
inst.Text = "Apply";
inst.CommandName = "apply";
inst.CommandArgument = s.Text;
//inst.ID = s.Text;
}
if (ActiveSkin != null && ActiveSkin.Name == s.Text)
{
Button inst = (Button)e.Item.FindControl("Button1");
inst.Text = "Rollback";
inst.CommandName = "remove";
inst.CommandArgument = s.Text;
//inst.ID = s.Text;
}
}
}
protected void SelectStarterKitDesign(object sender, EventArgs e)
{
if (((Button)sender).CommandName == "apply")
{
Skinning.ActivateAsCurrentSkin(Skin.CreateFromName(((Button)sender).CommandArgument));
this.Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())) + "?umbSkinning=true");
}
else if (((Button)sender).CommandName == "remove")
{
Template template = new Template(Node.GetCurrent().template);
Skinning.RollbackSkin(template.Id);
this.Page.Response.Redirect( library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())) +"?umbSkinning=true" );
}
else
{
Guid guid = new Guid(((Button)sender).CommandArgument);
InstalledPackage p = InstalledPackage.GetByGuid(guid.ToString());
if (p.Data.SkinRepoGuid != null && p.Data.SkinRepoGuid != Guid.Empty && p.Data.SkinRepoGuid.ToString() != repoGuid)
this.repo = cms.businesslogic.packager.repositories.Repository.getByGuid(p.Data.SkinRepoGuid.ToString());
Installer installer = new Installer();
if (this.repo.HasConnection())
{
Installer installer2 = new Installer();
string tempDir = installer2.Import(this.repo.fetch(guid.ToString()));
installer2.LoadConfig(tempDir);
int packageId = installer2.CreateManifest(tempDir, guid.ToString(), this.repoGuid);
installer2.InstallFiles(packageId, tempDir);
installer2.InstallBusinessLogic(packageId, tempDir);
installer2.InstallCleanUp(packageId, tempDir);
//NOTE: This seems excessive to have to re-load all content from the database here!?
library.RefreshContent();
Skinning.ActivateAsCurrentSkin(Skin.CreateFromName(((Button)sender).CommandName));
this.Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())) + "?umbSkinning=true");
}
else
{
this.ShowConnectionError();
}
}
}
protected void rep_starterKitDesignsLocal_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
if (ActiveSkin != null && ActiveSkin.Name == e.Item.DataItem.ToString())
{
Button inst = (Button)e.Item.FindControl("btnApply");
inst.Text = "Rollback";
inst.CommandName = "remove";
}
}
}
protected void SelectLocalStarterKitDesign(object sender, EventArgs e)
{
if (((Button)sender).CommandName == "apply")
{
Skinning.ActivateAsCurrentSkin(Skin.CreateFromName(((Button)sender).CommandArgument));
this.Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())) + "?umbSkinning=true");
}
else if (((Button)sender).CommandName == "remove")
{
Template template = new Template(Node.GetCurrent().template);
Skinning.RollbackSkin(template.Id);
this.Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())) + "?umbSkinning=true");
}
}
private void ShowConnectionError()
{
this.pnl_connectionerror.Visible = true;
}
}
}
| |
// 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.Sql.Fluent
{
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Sql.Fluent.Models;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.SqlDatabaseDefinition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Update;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseImportRequest.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseOperations.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseOperations.SqlDatabaseOperationsDefinition;
using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseThreatDetectionPolicy.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlElasticPool.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlServer.Definition;
using Microsoft.Azure.Management.Storage.Fluent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.Sql.Fluent.SqlSyncGroupOperations.SqlSyncGroupActionsDefinition;
/// <summary>
/// Implementation for SqlDatabase and its parent interfaces.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxEYXRhYmFzZUltcGw=
internal partial class SqlDatabaseImpl :
ChildResource<
Models.DatabaseInner,
Microsoft.Azure.Management.Sql.Fluent.SqlServerImpl,
Microsoft.Azure.Management.Sql.Fluent.ISqlServer>,
ISqlDatabase,
ISqlDatabaseDefinition<SqlServer.Definition.IWithCreate>,
SqlDatabase.Definition.IWithExistingDatabaseAfterElasticPool<SqlServer.Definition.IWithCreate>,
SqlDatabase.Definition.IWithStorageKeyAfterElasticPool<SqlServer.Definition.IWithCreate>,
SqlDatabase.Definition.IWithAuthenticationAfterElasticPool<SqlServer.Definition.IWithCreate>,
IUpdate,
SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool,
SqlDatabaseOperations.Definition.IWithStorageKeyAfterElasticPool,
SqlDatabaseOperations.Definition.IWithAuthenticationAfterElasticPool,
IWithCreateAfterElasticPoolOptions,
ISqlDatabaseOperationsDefinition
{
internal ISqlManager sqlServerManager;
internal string resourceGroupName;
internal string sqlServerName;
internal string sqlServerLocation;
private SqlElasticPoolImpl parentSqlElasticPool;
ICreatable<Microsoft.Azure.Management.Sql.Fluent.ISqlElasticPool> sqlElasticPoolCreatable;
private bool isPatchUpdate;
private ImportRequestInner importRequestInner;
private IStorageAccount storageAccount;
private readonly string name;
private SqlSyncGroupOperationsImpl syncGroupOps;
string ICreatable<ISqlDatabase>.Name => this.Name();
string IExternalChildResource<ISqlDatabase, ISqlServer>.Id => this.Id();
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="name">The name of this external child resource.</param>
/// <param name="parent">Reference to the parent of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param>
///GENMHASH:A35E7EC57FEC5C249FB11AEB50216560:C7DB22944BBAB9F9EBF4DC3ECB3D4098
internal SqlDatabaseImpl(string name, SqlServerImpl parent, DatabaseInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, parent)
{
if (parent == null)
{
throw new ArgumentNullException("parent");
}
this.name = name;
this.sqlServerManager = sqlServerManager ?? throw new ArgumentNullException("sqlServerManager");
this.resourceGroupName = parent.ResourceGroupName;
this.sqlServerName = parent.Name;
this.sqlServerLocation = parent.RegionName;
this.isPatchUpdate = false;
this.importRequestInner = null;
}
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="resourceGroupName">The resource group name.</param>
/// <param name="sqlServerName">The parent SQL server name.</param>
/// <param name="sqlServerLocation">The parent SQL server location.</param>
/// <param name="name">The name of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param>
///GENMHASH:F958650D21263F491EB84C4B1B980363:F9DB363750091A34604F0E5CF4D066EE
internal SqlDatabaseImpl(string resourceGroupName, string sqlServerName, string sqlServerLocation, string name, DatabaseInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, null)
{
this.name = name;
this.sqlServerManager = sqlServerManager ?? throw new ArgumentNullException("sqlServerManager");
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
this.isPatchUpdate = false;
this.importRequestInner = null;
}
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="name">The name of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param>
///GENMHASH:F958650D21263F491EB84C4B1B980363:F9DB363750091A34604F0E5CF4D066EE
internal SqlDatabaseImpl(string name, DatabaseInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, null)
{
this.name = name;
this.sqlServerManager = sqlServerManager ?? throw new ArgumentNullException("sqlServerManager");
this.isPatchUpdate = false;
this.importRequestInner = null;
}
public override string Name()
{
return this.name;
}
///GENMHASH:2AEEDA573EC9A50B62216BE3C228E186:9AC714CB5012CC7E3C25F0728F8230EB
public ISqlSyncGroupActionsDefinition SyncGroups()
{
if (this.syncGroupOps == null)
{
this.syncGroupOps = new SqlSyncGroupOperationsImpl(this, this.sqlServerManager);
}
return this.syncGroupOps;
}
///GENMHASH:A2A1505BCC6291F30BC2E2AC16639B19:5AFDD1B9912D08695516C8D33256ADB0
public SqlDatabaseImpl WithPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective)
{
return this.WithPremiumEdition(serviceObjective, SqlDatabasePremiumStorage.Max500Gb);
}
///GENMHASH:1B972C3D30942C7A2ABCC1A07A2FEE9C:BDE01F035BE7DAE356DF439B25414644
public SqlDatabaseImpl WithPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective, SqlDatabasePremiumStorage maxStorageCapacity)
{
this.Inner.Edition = DatabaseEditions.Premium;
this.WithServiceObjective(serviceObjective.Value);
this.Inner.MaxSizeBytes = $"{(long)maxStorageCapacity}";
return this;
}
///GENMHASH:C3E676C1E567606631528A28B60C9771:7EF1FF4D17AF9E55D4E99109A0950D18
public SqlDatabaseImpl WithEdition(string edition)
{
this.Inner.ElasticPoolName = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.Edition = edition;
return this;
}
///GENMHASH:376C162D9E950FA8A14B198790B45E34:5BF104F4489A5E42BAC27A2492EFC800
public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseUsageMetric> ListUsageMetrics()
{
return Extensions.Synchronize(() => this.ListUsageMetricsAsync());
}
///GENMHASH:D2C5B9B5EC8B12A40F6CC3A999383810:AA70F16BA24A6FB5F01832A54902603A
public Guid? CurrentServiceObjectiveId()
{
return this.Inner.CurrentServiceObjectiveId;
}
///GENMHASH:7EF1D1197B665941F65A1D87438FFF51:B4F8E60F3A870A52FB2020A6241D9F0F
public SqlDatabaseImpl WithExistingElasticPool(string elasticPoolName)
{
this.Inner.Edition = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.RequestedServiceObjectiveName = null;
this.Inner.ElasticPoolName = elasticPoolName;
return this;
}
///GENMHASH:3BDABC5AAC07959FD1C78BEA74FD8712:BA30DB47040BBC492DFC164A6C968F85
public SqlDatabaseImpl WithExistingElasticPool(ISqlElasticPool sqlElasticPool)
{
if (sqlElasticPool == null)
{
throw new ArgumentNullException("sqlElasticPool");
}
return this.WithExistingElasticPool(sqlElasticPool.Name);
}
///GENMHASH:32E35A609CF1108D0FC5FAAF9277C1AA:0A35F4FBFC584D98FAACCA25325781E8
public SqlDatabaseImpl WithTags(IDictionary<string,string> tags)
{
this.Inner.Tags = new Dictionary<string,string>(tags);
return this;
}
///GENMHASH:FCE70A9CD34B8C168EB1F63E6F207D42:BC43C8FF17726D8A07EA586F3B17608B
public SqlDatabaseImpl WithActiveDirectoryLoginAndPassword(string administratorLogin, string administratorPassword)
{
if (this.importRequestInner == null)
{
this.InitializeImportRequestInner();
}
this.importRequestInner.AuthenticationType = AuthenticationType.ADPassword;
this.importRequestInner.AdministratorLogin = administratorLogin;
this.importRequestInner.AdministratorLoginPassword = administratorPassword;
return this;
}
///GENMHASH:B793713C1E6696E957FDFDD58A692C32:6F6FD3F1EE6142188DD9CD51E89E8125
public ISqlDatabaseAutomaticTuning GetDatabaseAutomaticTuning()
{
var databaseAutomaticTuningInner = Extensions.Synchronize(() => this.sqlServerManager.Inner.DatabaseAutomaticTuning
.GetAsync(this.resourceGroupName, this.sqlServerName, this.Name()));
return databaseAutomaticTuningInner != null ? new SqlDatabaseAutomaticTuningImpl(this, databaseAutomaticTuningInner) : null;
}
///GENMHASH:68AE3BBF06B3A5F31F06F3A6A3469188:CF334608A3F1A8CD53872D1D3F94B016
public string DefaultSecondaryLocation()
{
return this.Inner.DefaultSecondaryLocation;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC
public string Id()
{
return this.Inner.Id;
}
public IReadOnlyDictionary<string, string> Tags()
{
return (Dictionary<string, string>) this.Inner.Tags;
}
///GENMHASH:09F37EE7E8975407273D6FA4FB12441D:5B750DDCC180A5B0F60DE4E3840E3CCB
public string Collation()
{
return this.Inner.Collation;
}
///GENMHASH:69A889F45F764B3E541DF980DABD1473:0C2A7DB4ABEFF325916B1EFB94934EC8
public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetricDefinition>> ListMetricDefinitionsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
List<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetricDefinition> databaseMetricDefinitions = new List<ISqlDatabaseMetricDefinition>();
var metricDefinitionInners = await this.sqlServerManager.Inner.Databases
.ListMetricDefinitionsAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
if (metricDefinitionInners != null)
{
foreach (var metricDefinitionInner in metricDefinitionInners)
{
databaseMetricDefinitions.Add(new SqlDatabaseMetricDefinitionImpl(metricDefinitionInner));
}
}
return databaseMetricDefinitions;
}
// Future reference when enabling the proper framework which will track dependencies
/////GENMHASH:7A9E1ACC5D9B5ED3EF93A2ABFD978F14:1F4B6D4F1D6BA088BF475B965981DC9B
//internal void AddParentDependency(IHasTaskGroup parentDependency)
//{
// this.AddDependency(parentDependency);
//}
///GENMHASH:FA6C4C8AE7729C6D128F00A0883B7A82:050D474227760B6267EFCEC6085DD2B2
public DateTime? EarliestRestoreDate()
{
return this.Inner.EarliestRestoreDate;
}
///GENMHASH:DF623B844EDAA9403C7ADB3E4D089ADD:1E1FA9AB1DCE4AD9527CF761EC52F4BC
public string RequestedServiceObjectiveName()
{
return this.Inner.RequestedServiceObjectiveName;
}
///GENMHASH:94274C9965DC54702B64A387A19F1F2B:B539D8C79F7F64123BCB4A6F10EDBD92
public IReadOnlyDictionary<string, Microsoft.Azure.Management.Sql.Fluent.IReplicationLink> ListReplicationLinks()
{
return Extensions.Synchronize(() => this.ListReplicationLinksAsync());
}
///GENMHASH:36003534781597C965476F5DF65AFAE0:5676358725D0EA511E36276932C4EE49
public SqlDatabaseImpl WithCollation(string collation)
{
this.Inner.Collation = collation;
return this;
}
///GENMHASH:0E666BFDFC9A666CA31FD735D7839414:6A8302C4C1400F1CDCE2686A7C6C8E41
public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.IDatabaseMetric> ListUsages()
{
// This method was deprecated in favor of the other database metric related methods
return new List<Microsoft.Azure.Management.Sql.Fluent.IDatabaseMetric>().AsReadOnly();
}
///GENMHASH:546F275F5C716DBA4B4E3ED283223400:0FDEDB5D39B9E6DEB193A84687780CDA
public SqlDatabaseImpl WithExistingSqlServer(string resourceGroupName, string sqlServerName, string sqlServerLocation)
{
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
return this;
}
///GENMHASH:A0EEAA3D4BFB322B5036FE92D9F0F641:1913C8F57081FC6BA71CCA1646434B22
public SqlDatabaseImpl WithExistingSqlServer(ISqlServer sqlServer)
{
if (sqlServer == null)
{
throw new ArgumentNullException("sqlServer");
}
this.resourceGroupName = sqlServer.ResourceGroupName;
this.sqlServerName = sqlServer.Name;
this.sqlServerLocation = sqlServer.RegionName;
return this;
}
///GENMHASH:B132DF15A736F615C9C36B19E938DF9E:65F2784364791089D5368B99F0100E95
public SqlDatabaseImpl WithStorageAccessKey(string storageAccessKey)
{
if (this.importRequestInner == null)
{
this.InitializeImportRequestInner();
}
this.importRequestInner.StorageKeyType = StorageKeyType.StorageAccessKey;
this.importRequestInner.StorageKey = storageAccessKey;
return this;
}
///GENMHASH:4A64D79C205DE76E07E6A3581CF5E14B:1A9338236EC82827DA9F8F8293BE39FE
public SqlElasticPoolForDatabaseImpl DefineElasticPool(string elasticPoolName)
{
this.parentSqlElasticPool = new SqlElasticPoolImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, elasticPoolName, new ElasticPoolInner(), this.sqlServerManager);
this.sqlElasticPoolCreatable = this.parentSqlElasticPool;
this.Inner.Edition = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.RequestedServiceObjectiveName = null;
this.Inner.ElasticPoolName = elasticPoolName;
return new SqlElasticPoolForDatabaseImpl(this, this.parentSqlElasticPool);
}
///GENMHASH:37206883074CEB63F8267ADE2545CF11:4C107A9D0C8600BD4F989BA7EE78EE0C
public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.IRestorePoint> ListRestorePoints()
{
return Extensions.Synchronize(() => this.ListRestorePointsAsync());
}
///GENMHASH:ED7351448838F0ED89C6E4AE8FB19EAE:E3FFCB76DD3743CD850897669FC40D12
public DateTime? CreationDate()
{
return this.Inner.CreationDate;
}
///GENMHASH:E1492A9309184FBF3CAF8F7F48E93B50:2131053C84548A7E9082276BD7E11BA6
public SqlDatabaseImpl WithStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective)
{
return this.WithStandardEdition(serviceObjective, SqlDatabaseStandardStorage.Max250Gb);
return this;
}
///GENMHASH:49E7BA88A31F5FA05707D7827931435B:83BE97DAEF89A7A6D0C78658DFEFCDE4
public SqlDatabaseImpl WithStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective, SqlDatabaseStandardStorage maxStorageCapacity)
{
this.Inner.Edition = DatabaseEditions.Standard;
this.WithServiceObjective(serviceObjective.Value);
this.Inner.MaxSizeBytes = $"{(long)maxStorageCapacity}";
return this;
}
///GENMHASH:FF80DD5A8C82E021759350836BD2FAD1:E70E0F84833F74462C0831B3C84D4A03
public SqlDatabaseImpl WithTag(string key, string value)
{
if (this.Inner.Tags == null)
{
this.Inner.Tags = new Dictionary<string, string>();
}
this.Inner.Tags.Add(key, value);
return this;
}
///GENMHASH:411E9B7C553E0F8FE64EB33DF4872E6A:A0F10EC124D07E925E3BE6285203F7E0
public string ServiceLevelObjective()
{
return this.Inner.ServiceLevelObjective;
}
///GENMHASH:6440992F4CBC2FF2069B36419334D933:F5264B18EE7543F8EA9233154894DE3C
private void InitializeImportRequestInner()
{
this.importRequestInner = new ImportRequestInner();
if (this.ElasticPoolName() != null)
{
this.importRequestInner.Edition = DatabaseEditions.Standard;
this.importRequestInner.ServiceObjectiveName = ServiceObjectiveName.S0;
this.importRequestInner.MaxSizeBytes = $"{(long)SqlDatabaseStandardStorage.Max250Gb}";
}
else
{
this.WithStandardEdition(SqlDatabaseStandardServiceObjective.S0);
}
}
///GENMHASH:7B6933FD706B12808B9D39A178094149:931378847EFB66ED97F43D824F04A3A3
public ISqlWarehouse AsWarehouse()
{
if (this.IsDataWarehouse())
{
if (this.Parent != null)
{
return new SqlWarehouseImpl(this.Name(), this.Parent, this.Inner, this.sqlServerManager);
}
else
{
return new SqlWarehouseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, this.Name(), this.Inner, this.sqlServerManager);
}
}
return null;
}
///GENMHASH:39034E92B8596ED5F36CD108B4CEBBC8:A785C9F7D890C95E8D7E8BE08BA1DB7D
public SqlDatabaseThreatDetectionPolicyImpl DefineThreatDetectionPolicy(string policyName)
{
return new SqlDatabaseThreatDetectionPolicyImpl(policyName, this, new DatabaseSecurityAlertPolicyInner(), this.sqlServerManager);
}
///GENMHASH:F5717DCDC59DCEC39989A49248CA5245:C44735502B6EFAF1B34E5E521F088541
public SqlDatabaseImpl WithoutElasticPool()
{
this.Inner.ElasticPoolName = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.RequestedServiceObjectiveName = null;
return this;
}
///GENMHASH:547C5E4F79BCDF43D68C1D68B8233E56:0417368F07CF88E0DF418E9E5F74D9AE
public bool IsDataWarehouse()
{
return this.Inner.Edition != null ? this.Inner.Edition.Equals(DatabaseEditions.DataWarehouse, StringComparison.OrdinalIgnoreCase) : false;
}
///GENMHASH:8380741288B285433B6443AF2F466E6D:A0411F0E7FF3C97800E30DDE842787ED
public async Task<IReadOnlyDictionary<string, Microsoft.Azure.Management.Sql.Fluent.IServiceTierAdvisor>> ListServiceTierAdvisorsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Dictionary<string, Microsoft.Azure.Management.Sql.Fluent.IServiceTierAdvisor> serviceTierAdvisors = new Dictionary<string, IServiceTierAdvisor>();
var serviceTierAdvisorInners = await this.sqlServerManager.Inner.ServiceTierAdvisors
.ListByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
if (serviceTierAdvisorInners != null)
{
foreach (var serviceTierAdvisorInner in serviceTierAdvisorInners)
{
serviceTierAdvisors.Add(serviceTierAdvisorInner.Name, new ServiceTierAdvisorImpl(this.resourceGroupName, this.sqlServerName, serviceTierAdvisorInner, this.sqlServerManager));
}
}
return serviceTierAdvisors;
}
///GENMHASH:6A2970A94B2DD4A859B00B9B9D9691AD:E33B754A9A9CD4E144011EFCD75AA27C
public Region Region()
{
return Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region.Create(this.RegionName());
}
///GENMHASH:06F61EC9451A16F634AEB221D51F2F8C:1ABA34EF946CBD0278FAD778141792B2
public string Status()
{
return this.Inner.Status;
}
///GENMHASH:957BA7B4E61C9B91983ED17E2B61DBD7:9549FCCFE13908133153A6585989F147
public string ElasticPoolName()
{
return this.Inner.ElasticPoolName;
}
///GENMHASH:0D23B35B24D1777140585D16F513A57E:7924D48B71636A56E44F69FD03C4DFA9
internal SqlDatabaseImpl WithPatchUpdate()
{
this.isPatchUpdate = true;
return this;
}
///GENMHASH:396EF11BF84C5A5AEDE59746D18EF7FA:DFA427061784001F9E768D7BEB7A5E43
public SqlDatabaseImpl WithServiceObjective(string serviceLevelObjective)
{
this.Inner.ElasticPoolName = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.RequestedServiceObjectiveName = serviceLevelObjective;
return this;
}
///GENMHASH:645835BFC7B3F763E704B19D0547F1DE:CD2A5AB12BE2F4D02FD565EE2DEA70FE
public async Task<IReadOnlyDictionary<string, Microsoft.Azure.Management.Sql.Fluent.IReplicationLink>> ListReplicationLinksAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Dictionary<string, Microsoft.Azure.Management.Sql.Fluent.IReplicationLink> replicationLinks = new Dictionary<string, IReplicationLink>();
var replicationLinkInners = await this.sqlServerManager.Inner.ReplicationLinks
.ListByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
if (replicationLinkInners != null)
{
foreach (var replicationLinkInner in replicationLinkInners)
{
replicationLinks.Add(replicationLinkInner.Name, new ReplicationLinkImpl(this.resourceGroupName, this.sqlServerName, replicationLinkInner, this.sqlServerManager));
}
}
return replicationLinks;
}
///GENMHASH:F340B9C68B7C557DDB54F615FEF67E89:3054A3D10ED7865B89395E7C007419C9
public string RegionName()
{
return this.Inner.Location;
}
///GENMHASH:F5BFC9500AE4C04846BAAD2CC50792B3:DA87C4AB3EEB9D4BA746DF610E8BC39F
public string Edition()
{
return this.Inner.Edition;
}
///GENMHASH:1A8677F2439B3D7CABE292785BD60427:5F04DB72C29FE210E63C4F7C53799BA7
public SqlDatabaseImpl ImportFrom(string storageUri)
{
this.InitializeImportRequestInner();
this.importRequestInner.StorageUri = storageUri;
return this;
}
///GENMHASH:7373E32C16A40BA46FE99D3C43267A6D:51DAE7A41E58631741DFE52C7C67E106
public SqlDatabaseImpl ImportFrom(IStorageAccount storageAccount, string containerName, string fileName)
{
if (storageAccount == null)
{
throw new ArgumentNullException("storageAccount");
}
if (containerName == null)
{
throw new ArgumentNullException("containerName");
}
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
this.InitializeImportRequestInner();
this.storageAccount = storageAccount;
this.importRequestInner.StorageUri = $"{containerName}/{fileName}";
return this;
}
///GENMHASH:C8BF6EB45120AB5638A39B9E6F246F48:88685B211625AC25043E56EF15C881D0
public async Task<Microsoft.Azure.Management.Sql.Fluent.ITransparentDataEncryption> GetTransparentDataEncryptionAsync(CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var transparentDataEncryptionInner = await this.sqlServerManager.Inner.TransparentDataEncryptions
.GetAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
return transparentDataEncryptionInner != null ? new TransparentDataEncryptionImpl(this.resourceGroupName, this.sqlServerName, transparentDataEncryptionInner, this.sqlServerManager) : null;
}
catch (CloudException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
catch (AggregateException ex)
{
if(ex.InnerExceptions != null)
{
var cloudEx = (CloudException) ex.InnerExceptions.FirstOrDefault(e => e is CloudException);
if(cloudEx != null &&
cloudEx.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
throw ex;
}
}
///GENMHASH:B23645FC2F779DBC6F44B880C488B561:EEF0AD33D842F97FF9BE1E629E1C03EE
public SqlDatabaseImpl WithMaxSizeBytes(long maxSizeBytes)
{
this.Inner.MaxSizeBytes = $"{maxSizeBytes}";
return this;
}
///GENMHASH:2E256CC1ACCA4253233F61C79F9D712E:9790D012FA64E47343F12DB13F0AA212
public IUpgradeHintInterface GetUpgradeHint()
{
// This method was deprecated; service returns null
return null;
}
///GENMHASH:A26C8D278B6519B28BA17D3966024017:A4AA33E1BB3D9FE5155733094177C7C2
public long MaxSizeBytes()
{
return Convert.ToInt64(this.Inner.MaxSizeBytes ?? "0");
}
///GENMHASH:A1DBAE6CBFB56230E32A4169F4FC18B2:75E99B1B89E418875225D1E0E9BECAAE
public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetric> ListMetrics(string filter)
{
return Extensions.Synchronize(() => this.ListMetricsAsync(filter));
}
///GENMHASH:FB41F80AEFA7E12022C9196F41BF8921:ED8B3A06AA34CEDC5610A3DEF09E3EEE
public SqlDatabaseImpl WithBasicEdition()
{
return this.WithBasicEdition(SqlDatabaseBasicStorage.Max2Gb);
}
///GENMHASH:F7B4B7D42B00968BBE7591CAAB07FB08:D7C7D124B191508D782E83C2EA9D3650
public SqlDatabaseImpl WithBasicEdition(SqlDatabaseBasicStorage maxStorageCapacity)
{
this.Inner.Edition = DatabaseEditions.Basic;
this.WithServiceObjective(ServiceObjectiveName.Basic);
this.WithMaxSizeBytes((long)maxStorageCapacity);
return this;
}
///GENMHASH:E79C534DFF1FD292BF3629BFBDD6B6B9:96B4434F4DABBF823E846088675F0311
public SqlDatabaseImportRequestImpl ImportBacpac(string storageUri)
{
if (storageUri == null)
{
throw new ArgumentNullException("storageUri");
}
return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager)
.ImportFrom(storageUri);
}
///GENMHASH:E67F1FD4894329ACCDFF54905A1E694E:7EE85AF9D02D1E0432372E41F59DAC1E
public SqlDatabaseImportRequestImpl ImportBacpac(IStorageAccount storageAccount, string containerName, string fileName)
{
if (storageAccount == null)
{
throw new ArgumentNullException("storageAccount");
}
if (containerName == null)
{
throw new ArgumentNullException("containerName");
}
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager)
.ImportFrom(storageAccount, containerName, fileName);
}
///GENMHASH:D07614EC964723EC7E563278F8FD0BE6:9903ECC9F8F5837D63A44DAA11F79C8E
public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseUsageMetric>> ListUsageMetricsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
List<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseUsageMetric> usageMetricList = new List<ISqlDatabaseUsageMetric>();
var databaseUsageInners = await this.sqlServerManager.Inner.DatabaseUsages
.ListByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
if (databaseUsageInners != null)
{
foreach (var databaseUsageInner in databaseUsageInners)
{
usageMetricList.Add(new SqlDatabaseUsageMetricImpl(databaseUsageInner));
}
}
return usageMetricList.AsReadOnly();
}
///GENMHASH:41180B8AE28244EF8581E555D8B35D2B:59963B0DFB54839D345581B895AFA980
public string DatabaseId()
{
return this.Inner.DatabaseId.ToString();
}
///GENMHASH:498D3951D3EB5A31E765F1E9A24A877E:6992EC71A319B4CAEF905C374DF6F78C
public SqlDatabaseImpl WithSharedAccessKey(string sharedAccessKey)
{
if (this.importRequestInner == null)
{
this.InitializeImportRequestInner();
}
this.importRequestInner.StorageKeyType = StorageKeyType.SharedAccessKey;
this.importRequestInner.StorageKey = sharedAccessKey;
return this;
}
///GENMHASH:CA0DDA4D9821F262B350AF8BD2FD3D72:90A235C564BCEA582EA7E8E169017608
public ISqlDatabaseThreatDetectionPolicy GetThreatDetectionPolicy()
{
try
{
var policyInner = Extensions.Synchronize(() => this.sqlServerManager.Inner.DatabaseThreatDetectionPolicies
.GetAsync(this.resourceGroupName, this.sqlServerName, this.Name()));
return policyInner != null ? new SqlDatabaseThreatDetectionPolicyImpl(policyInner.Name, this, policyInner, this.sqlServerManager) : null;
}
catch (CloudException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
catch (AggregateException ex)
{
if(ex.InnerExceptions != null)
{
var cloudEx = (CloudException) ex.InnerExceptions.FirstOrDefault(e => e is CloudException);
if(cloudEx != null &&
cloudEx.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
throw ex;
}
}
///GENMHASH:E9EDBD2E8DC2C547D1386A58778AA6B9:7EBD4102FEBFB0AD7091EA1ACBD84F8B
public string ResourceGroupName()
{
return this.resourceGroupName;
}
///GENMHASH:A521981B274EF2B3D621C0705EFAA811:5E9BEFBB11C2769CA5132E0CF9CCABB2
public SqlDatabaseImpl WithMode(string createMode)
{
this.Inner.CreateMode = createMode;
return this;
}
///GENMHASH:2345D3E100BA4B78504A2CC57A361F1E:250EC2907300FFA6125F7205F03A3E7F
public SqlDatabaseImpl WithoutTag(string key)
{
this.Inner.Tags.Remove(key);
return this;
}
///GENMHASH:61F5809AB3B985C61AC40B98B1FBC47E:998832D58C98F6DCF3637916D2CC70B9
public string SqlServerName()
{
return this.sqlServerName;
}
///GENMHASH:E181EA037CDEB6D9DCE12CA92D1526C7:0D2A486B784948E9672C737F8A7624D2
public SqlDatabaseImpl FromSample(SampleName sampleName)
{
this.Inner.SampleName = sampleName.Value;
return this;
}
///GENMHASH:F558A35AAC7463E4988A0A5E052953DD:BFCA5ABF1F9698290D6F011B01A4BC1F
public ITransparentDataEncryption GetTransparentDataEncryption()
{
return Extensions.Synchronize(() => this.GetTransparentDataEncryptionAsync());
}
///GENMHASH:86135EF83A124C4DC11F0F4D3932D96D:D2635043C832D0ED57B4C7331890CFBC
public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetric>> ListMetricsAsync(string filter, CancellationToken cancellationToken = default(CancellationToken))
{
List<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetric> dbMetrics = new List<ISqlDatabaseMetric>();
var metricInners = await this.sqlServerManager.Inner.Databases
.ListMetricsAsync(this.resourceGroupName, this.sqlServerName, this.Name(), filter, cancellationToken);
if (metricInners != null)
{
foreach (var metricInner in metricInners)
{
dbMetrics.Add(new SqlDatabaseMetricImpl(metricInner));
}
}
return dbMetrics.AsReadOnly();
}
///GENMHASH:495111B1D55D7AA3C4EA4E49042FA05A:018B4F53394EF9D955345603E5AF968D
public SqlDatabaseImpl WithNewElasticPool(ICreatable<Microsoft.Azure.Management.Sql.Fluent.ISqlElasticPool> sqlElasticPool)
{
if (sqlElasticPool == null)
{
throw new ArgumentNullException("sqlElasticPool");
}
this.sqlElasticPoolCreatable = sqlElasticPool;
this.parentSqlElasticPool = (SqlElasticPoolImpl)sqlElasticPool;
this.Inner.Edition = null;
this.Inner.RequestedServiceObjectiveId = null;
this.Inner.RequestedServiceObjectiveName = null;
this.Inner.ElasticPoolName = parentSqlElasticPool.Name();
// Future dependency tracking note
// this.AddDependency(sqlElasticPool);
return this;
}
///GENMHASH:F5DF37BD82C1C590C56B4F013C07DABC:8C97E5D1BC323EC4701C62A50021CBF3
public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseMetricDefinition> ListMetricDefinitions()
{
return Extensions.Synchronize(() => this.ListMetricDefinitionsAsync());
}
///GENMHASH:E5ABDAE624DDFF518B3732327DAE080E:4F48A6821129951A21572526EC7AD923
public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabase> RenameAsync(string newDatabaseName, CancellationToken cancellationToken = default(CancellationToken))
{
ResourceId resourceId = ResourceId.FromString(this.Id());
String newId = $"{resourceId.Parent.Id}/databases/{newDatabaseName}";
await this.sqlServerManager.Inner.Databases
.RenameAsync(this.resourceGroupName, this.sqlServerName, this.Name(), newId, cancellationToken);
return await this.sqlServerManager.SqlServers.Databases
.GetBySqlServerAsync(this.resourceGroupName, this.sqlServerName, newDatabaseName, cancellationToken);
}
///GENMHASH:85FBE37563F3ADEA0037149593562508:FFD4FFA925AA8688B4B8288DE2CD55F3
public SqlDatabaseImpl FromRestorableDroppedDatabase(ISqlRestorableDroppedDatabase restorableDroppedDatabase)
{
if (restorableDroppedDatabase == null)
{
throw new ArgumentNullException("restorableDroppedDatabase");
}
return this.WithSourceDatabase(restorableDroppedDatabase.Id)
.WithMode(CreateMode.Restore);
}
///GENMHASH:F6C12109AEE137840B60E059E6708A02:3802C120362CEFDF42D356C4A1BB4C0B
public SqlDatabaseImpl FromRestorePoint(IRestorePoint restorePoint)
{
if (restorePoint == null)
{
throw new ArgumentNullException("restorePoint");
}
this.Inner.RestorePointInTime = restorePoint.EarliestRestoreDate;
return this.WithSourceDatabase(restorePoint.DatabaseId)
.WithMode(CreateMode.PointInTimeRestore);
return this;
}
///GENMHASH:65DFD5CF3EED2BB07512CC188E7D8F8A:668E0DBB00202029F024E9733E6C0BD2
public SqlDatabaseImpl FromRestorePoint(IRestorePoint restorePoint, DateTime restorePointDateTime)
{
this.Inner.RestorePointInTime = restorePointDateTime;
return this.WithSourceDatabase(restorePoint.DatabaseId)
.WithMode(CreateMode.PointInTimeRestore);
}
///GENMHASH:7A0398C4BB6EBF42CC817EE638D40E9C:BF44555315B4D8F7DE5B31B09438FA0A
public string ParentId()
{
var resourceId = ResourceId.FromString(this.Id());
return resourceId?.Parent?.Id;
}
///GENMHASH:75380AC1C8F8C473AF028534126AA5D4:25C18B002519A132E6FD1BDD0AAEAC82
public ISqlDatabase Rename(string newDatabaseName)
{
return Extensions.Synchronize(() => this.RenameAsync(newDatabaseName));
}
///GENMHASH:7E720FDC940A2922809B9D27EFCACBCD:47BE206E881D06DAD00CE167DAE60229
public SqlDatabaseImpl WithSqlAdministratorLoginAndPassword(string administratorLogin, string administratorPassword)
{
if (this.importRequestInner == null)
{
this.InitializeImportRequestInner();
}
this.importRequestInner.AuthenticationType = AuthenticationType.SQL;
this.importRequestInner.AdministratorLogin = administratorLogin;
this.importRequestInner.AdministratorLoginPassword = administratorPassword;
return this;
}
///GENMHASH:212A2F2F92E2D462C22479742BC730A3:A93678FA285496CB5F325AF4DC1B281C
public SqlDatabaseExportRequestImpl ExportTo(string storageUri)
{
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.ExportTo(storageUri);
}
///GENMHASH:86E7BAA14B4627C99B23DD5E99D3E137:E50A2EC6A3EE3A525FA469BD438C0871
public SqlDatabaseExportRequestImpl ExportTo(IStorageAccount storageAccount, string containerName, string fileName)
{
if (storageAccount == null)
{
throw new ArgumentNullException("storageAccount");
}
if (containerName == null)
{
throw new ArgumentNullException("containerName");
}
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.ExportTo(storageAccount, containerName, fileName);
}
///GENMHASH:1F5324043331585B2120A5C89F84F5DB:C885DEE02CF75EE1A4A387AAA0D8A760
public SqlDatabaseExportRequestImpl ExportTo(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> storageAccountCreatable, string containerName, string fileName)
{
if (storageAccountCreatable == null)
{
throw new ArgumentNullException("storageAccountCreatable");
}
if (containerName == null)
{
throw new ArgumentNullException("containerName");
}
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.ExportTo(storageAccountCreatable, containerName, fileName);
}
///GENMHASH:B1D3E971A2C4574ED03F74E5745E8301:B5D8E6907D7456C71BFBDDD84D4CAF3D
public Guid? RequestedServiceObjectiveId()
{
return this.Inner.RequestedServiceObjectiveId;
}
///GENMHASH:EB950732E887990C7D61B74EBA2E3E50:573BDC9A38C91E0EA3771EF31E937127
public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.IRestorePoint>> ListRestorePointsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
List<Microsoft.Azure.Management.Sql.Fluent.IRestorePoint> restorePoints = new List<IRestorePoint>();
var restorePointInners = await this.sqlServerManager.Inner.RestorePoints
.ListByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
if (restorePointInners != null)
{
foreach (var restorePointInner in restorePointInners)
{
restorePoints.Add(new RestorePointImpl(this.resourceGroupName, this.sqlServerName, restorePointInner));
}
}
return restorePoints.AsReadOnly();
}
///GENMHASH:F8954D151717AC497C4A3B76321952A6:5BEB5EA8B9F53B7F9AA00D61AB0B2853
public SqlDatabaseImpl WithSourceDatabase(string sourceDatabaseId)
{
this.Inner.SourceDatabaseId = sourceDatabaseId;
return this;
}
///GENMHASH:642F972C91F9E70B14E53881C1FCA8F9:F069850B2BE457D02CB713E8708DE59C
public SqlDatabaseImpl WithSourceDatabase(ISqlDatabase sourceDatabase)
{
if (sourceDatabase == null)
{
throw new ArgumentNullException("sourcedatabase");
}
return this.WithSourceDatabase(sourceDatabase.Id);
}
///GENMHASH:6F25566A2BEBF8E935396FF70D7412F6:CFB98BD6B2251258A7E6ED7109B50D5A
public IReadOnlyDictionary<string, Microsoft.Azure.Management.Sql.Fluent.IServiceTierAdvisor> ListServiceTierAdvisors()
{
return Extensions.Synchronize(() => this.ListServiceTierAdvisorsAsync());
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:AA78F52D96EC68C22A95FE39F9EB7071
protected async Task<Models.DatabaseInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.sqlServerManager.Inner.Databases.GetAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken: cancellationToken);
}
///GENMHASH:9557699E7EE892CCCC89A074E0915333:A55D3CBCED3C2D7241CB8E96C4D3F217
public async Task BeforeGroupCreateOrUpdateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (this.importRequestInner != null && this.storageAccount != null)
{
var storageKeys = await storageAccount.GetKeysAsync(cancellationToken);
if (storageKeys == null || storageKeys.Count == 0)
{
throw new Exception("Failed to retrieve Storage Account Keys");
}
var storageAccountKey = storageKeys[0].Value;
this.importRequestInner.StorageUri = $"{this.storageAccount?.EndPoints?.Primary?.Blob}{this.importRequestInner.StorageUri}";
this.importRequestInner.StorageKeyType = StorageKeyType.StorageAccessKey;
this.importRequestInner.StorageKey = storageAccountKey;
}
if (this.sqlElasticPoolCreatable != null)
{
this.parentSqlElasticPool = (SqlElasticPoolImpl)await this.sqlElasticPoolCreatable.CreateAsync(cancellationToken);
}
else if (this.Inner.ElasticPoolName != null && this.importRequestInner != null)
{
this.parentSqlElasticPool = (SqlElasticPoolImpl) await this.sqlServerManager.SqlServers.ElasticPools
.GetBySqlServerAsync(this.resourceGroupName, this.sqlServerName, this.Inner.ElasticPoolName, cancellationToken);
}
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:4E95DB8FD4DE0A3758B25CB7991A2C2A
public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabase> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await BeforeGroupCreateOrUpdateAsync(cancellationToken);
this.Inner.Location = this.sqlServerLocation;
if (this.importRequestInner != null)
{
this.importRequestInner.DatabaseName = this.Name();
if (this.importRequestInner.Edition == null)
{
this.importRequestInner.Edition = this.Inner.Edition;
}
if (this.importRequestInner.ServiceObjectiveName == null)
{
this.importRequestInner.ServiceObjectiveName = this.Inner.RequestedServiceObjectiveName;
}
if (this.importRequestInner.MaxSizeBytes == null)
{
this.importRequestInner.MaxSizeBytes = this.Inner.MaxSizeBytes;
}
var dbInner = this.sqlServerManager.Inner.Databases
.ImportAsync(this.resourceGroupName, this.sqlServerName, this.importRequestInner, cancellationToken);
if (this.Inner.ElasticPoolName == null)
{
return await this.RefreshAsync(cancellationToken);
}
return this;
}
else
{
var dbInner = await this.sqlServerManager.Inner.Databases
.CreateOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.Name(), this.Inner, cancellationToken);
this.SetInner(dbInner);
return this;
}
await AfterPostRunAsync(cancellationToken);
}
///GENMHASH:AC7CC07C6D6A5043B63254841EEBA63A:7F7F8CAB431C433CEC91CF27F54FEFFD
public async Task AfterPostRunAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (this.importRequestInner != null && this.parentSqlElasticPool != null)
{
this.isPatchUpdate = true;
await this.UpdateResourceAsync(cancellationToken);
}
this.isPatchUpdate = false;
this.importRequestInner = null;
this.storageAccount = null;
this.sqlElasticPoolCreatable = null;
}
///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:6BCBA570417EAC0D10DCE422CAB270A5
public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabase> UpdateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (this.isPatchUpdate)
{
DatabaseUpdateInner databaseUpdateInner = new DatabaseUpdateInner()
{
Tags = this.Inner.Tags,
Collation = this.Inner.Collation,
SourceDatabaseId = this.Inner.SourceDatabaseId,
CreateMode = this.Inner.CreateMode,
Edition = this.Inner.Edition,
RequestedServiceObjectiveName = this.Inner.RequestedServiceObjectiveName,
MaxSizeBytes = this.Inner.MaxSizeBytes,
ElasticPoolName = this.Inner.ElasticPoolName,
Location = this.sqlServerLocation
};
await this.sqlServerManager.Inner.Databases.UpdateAsync(this.resourceGroupName, this.sqlServerName, this.Name(), databaseUpdateInner, cancellationToken);
await this.RefreshAsync(cancellationToken);
return this;
}
else
{
return await this.CreateResourceAsync(cancellationToken);
}
}
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:8FF06E289719BB519BDB4F57C1488F6F
public SqlServerImpl Attach()
{
return Parent;
}
///GENMHASH:65E6085BB9054A86F6A84772E3F5A9EC:B8443F1744F97B6579E4964E67592EFB
public void Delete()
{
Extensions.Synchronize(() => this.DeleteAsync());
}
///GENMHASH:0FEDA307DAD2022B36843E8905D26EAD:95BA1017B6D636BB0934427C9B74AB8D
public async Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.DeleteResourceAsync(cancellationToken);
}
///GENMHASH:E24A9768E91CD60E963E43F00AA1FDFE:774D147C034A0076F237A117323E70D7
public async Task DeleteResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.sqlServerManager.Inner.Databases
.DeleteAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
}
///GENMHASH:6BCE517E09457FF033728269C8936E64:ECB4548536225101A4FBA7DFDB22FE6D
public SqlDatabaseImpl Update()
{
// Future reference when enabling the proper framework which will track dependencies
// This is the beginning of the update flow
// super.PrepareUpdate();
return this;
}
public ISqlDatabase Apply()
{
return Extensions.Synchronize(() => this.ApplyAsync());
}
public async Task<ISqlDatabase> ApplyAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true)
{
return await this.UpdateResourceAsync(cancellationToken);
}
public ISqlDatabase Create()
{
return Extensions.Synchronize(() => this.CreateAsync());
}
public async Task<ISqlDatabase> CreateAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true)
{
return await this.CreateResourceAsync(cancellationToken);
}
public ISqlDatabase Refresh()
{
return Extensions.Synchronize(() => this.RefreshAsync());
}
public async Task<ISqlDatabase> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.SetInner(await this.GetInnerAsync(cancellationToken));
return this;
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/log.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/log.proto</summary>
public static partial class LogReflection {
#region Descriptor
/// <summary>File descriptor for google/api/log.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LogReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChRnb29nbGUvYXBpL2xvZy5wcm90bxIKZ29vZ2xlLmFwaRoWZ29vZ2xlL2Fw",
"aS9sYWJlbC5wcm90byJ1Cg1Mb2dEZXNjcmlwdG9yEgwKBG5hbWUYASABKAkS",
"KwoGbGFiZWxzGAIgAygLMhsuZ29vZ2xlLmFwaS5MYWJlbERlc2NyaXB0b3IS",
"EwoLZGVzY3JpcHRpb24YAyABKAkSFAoMZGlzcGxheV9uYW1lGAQgASgJQmoK",
"DmNvbS5nb29nbGUuYXBpQghMb2dQcm90b1ABWkVnb29nbGUuZ29sYW5nLm9y",
"Zy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9zZXJ2aWNlY29uZmlnO3NlcnZp",
"Y2Vjb25maWeiAgRHQVBJYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.LabelReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.LogDescriptor), global::Google.Api.LogDescriptor.Parser, new[]{ "Name", "Labels", "Description", "DisplayName" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A description of a log type. Example in YAML format:
///
/// - name: library.googleapis.com/activity_history
/// description: The history of borrowing and returning library items.
/// display_name: Activity
/// labels:
/// - key: /customer_id
/// description: Identifier of a library customer
/// </summary>
public sealed partial class LogDescriptor : pb::IMessage<LogDescriptor>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<LogDescriptor> _parser = new pb::MessageParser<LogDescriptor>(() => new LogDescriptor());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<LogDescriptor> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.LogReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LogDescriptor() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LogDescriptor(LogDescriptor other) : this() {
name_ = other.name_;
labels_ = other.labels_.Clone();
description_ = other.description_;
displayName_ = other.displayName_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LogDescriptor Clone() {
return new LogDescriptor(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the log. It must be less than 512 characters long and can
/// include the following characters: upper- and lower-case alphanumeric
/// characters [A-Za-z0-9], and punctuation characters including
/// slash, underscore, hyphen, period [/_-.].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Api.LabelDescriptor> _repeated_labels_codec
= pb::FieldCodec.ForMessage(18, global::Google.Api.LabelDescriptor.Parser);
private readonly pbc::RepeatedField<global::Google.Api.LabelDescriptor> labels_ = new pbc::RepeatedField<global::Google.Api.LabelDescriptor>();
/// <summary>
/// The set of labels that are available to describe a specific log entry.
/// Runtime requests that contain labels not specified here are
/// considered invalid.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Api.LabelDescriptor> Labels {
get { return labels_; }
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 3;
private string description_ = "";
/// <summary>
/// A human-readable description of this log. This information appears in
/// the documentation and can contain details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 4;
private string displayName_ = "";
/// <summary>
/// The human-readable name for this log. This information appears on
/// the user interface and should be concise.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as LogDescriptor);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(LogDescriptor other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if(!labels_.Equals(other.labels_)) return false;
if (Description != other.Description) return false;
if (DisplayName != other.DisplayName) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= labels_.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
labels_.WriteTo(output, _repeated_labels_codec);
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(34);
output.WriteString(DisplayName);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
labels_.WriteTo(ref output, _repeated_labels_codec);
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(34);
output.WriteString(DisplayName);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += labels_.CalculateSize(_repeated_labels_codec);
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(LogDescriptor other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
labels_.Add(other.labels_);
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
labels_.AddEntriesFrom(input, _repeated_labels_codec);
break;
}
case 26: {
Description = input.ReadString();
break;
}
case 34: {
DisplayName = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
labels_.AddEntriesFrom(ref input, _repeated_labels_codec);
break;
}
case 26: {
Description = input.ReadString();
break;
}
case 34: {
DisplayName = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
// 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.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System
{
public partial class Uri
{
//
// All public ctors go through here
//
private void CreateThis(string uri, bool dontEscape, UriKind uriKind)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
_string = uri == null ? string.Empty : uri;
if (dontEscape)
_flags |= Flags.UserEscaped;
ParsingError err = ParseScheme(_string, ref _flags, ref _syntax);
UriFormatException e;
InitializeUri(err, uriKind, out e);
if (e != null)
throw e;
}
private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e)
{
if (err == ParsingError.None)
{
if (IsImplicitFile)
{
// V1 compat
// A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and
// uriKind != Absolute
// A relative Uri wins over implicit Unix path unless uriKind == Absolute
if (NotAny(Flags.DosPath) &&
uriKind != UriKind.Absolute &&
((uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\')))
|| (!IsWindowsSystem && InFact(Flags.UnixPath))))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otherwise an absolute file Uri wins when it's of the form "\\something"
}
//
// V1 compat issue
// We should support relative Uris of the form c:\bla or c:/bla
//
else if (uriKind == UriKind.Relative && InFact(Flags.DosPath))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otherwise an absolute file Uri wins when it's of the form "c:\something"
}
}
}
else if (err > ParsingError.LastRelativeUriOkErrIndex)
{
//This is a fatal error based solely on scheme name parsing
_string = null; // make it be invalid Uri
e = GetException(err);
return;
}
bool hasUnicode = false;
_iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing)));
if (_iriParsing &&
(CheckForUnicode(_string) || CheckForEscapedUnreserved(_string)))
{
_flags |= Flags.HasUnicode;
hasUnicode = true;
// switch internal strings
_originalUnicodeString = _string; // original string location changed
}
if (_syntax != null)
{
if (_syntax.IsSimple)
{
if ((err = PrivateParseMinimal()) != ParsingError.None)
{
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
{
// RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri.
_syntax = null; // convert to relative uri
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
return;
}
else
e = GetException(err);
}
else if (uriKind == UriKind.Relative)
{
// Here we know that we can create an absolute Uri, but the user has requested only a relative one
e = GetException(ParsingError.CannotCreateRelative);
}
else
e = null;
// will return from here
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
else
{
// offer custom parser to create a parsing context
_syntax = _syntax.InternalOnNewUri();
// in case they won't call us
_flags |= Flags.UserDrivenParsing;
// Ask a registered type to validate this uri
_syntax.InternalValidate(this, out e);
if (e != null)
{
// Can we still take it as a relative Uri?
if (uriKind != UriKind.Absolute && err != ParsingError.None
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
_syntax = null; // convert it to relative
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
}
}
else // e == null
{
if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion))
{
// User parser took over on an invalid Uri
SetUserDrivenParsing();
}
else if (uriKind == UriKind.Relative)
{
// Here we know that custom parser can create an absolute Uri, but the user has requested only a
// relative one
e = GetException(ParsingError.CannotCreateRelative);
}
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
// will return from here
}
}
// If we encountered any parsing errors that indicate this may be a relative Uri,
// and we'll allow relative Uri's, then create one.
else if (err != ParsingError.None && uriKind != UriKind.Absolute
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
e = null;
_flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri
if (_iriParsing && hasUnicode)
{
// Iri'ze and then normalize relative uris
_string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length,
(UriComponents)0);
}
}
else
{
_string = null; // make it be invalid Uri
e = GetException(err);
}
}
//
// Unescapes entire string and checks if it has unicode chars
//
private bool CheckForUnicode(string data)
{
for (int i = 0; i < data.Length; i++)
{
char c = data[i];
if (c == '%')
{
if (i + 2 < data.Length)
{
if (UriHelper.EscapedAscii(data[i + 1], data[i + 2]) > 0x7F)
{
return true;
}
i += 2;
}
}
else if (c > 0x7F)
{
return true;
}
}
return false;
}
// Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped.
private unsafe bool CheckForEscapedUnreserved(string data)
{
fixed (char* tempPtr = data)
{
for (int i = 0; i < data.Length - 2; ++i)
{
if (tempPtr[i] == '%' && IsHexDigit(tempPtr[i + 1]) && IsHexDigit(tempPtr[i + 2])
&& tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F
{
char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]);
if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch))
{
return true;
}
}
}
}
return false;
}
//
// Returns true if the string represents a valid argument to the Uri ctor
// If uriKind != AbsoluteUri then certain parsing errors are ignored but Uri usage is limited
//
public static bool TryCreate(string uriString, UriKind uriKind, out Uri result)
{
if ((object)uriString == null)
{
result = null;
return false;
}
UriFormatException e = null;
result = CreateHelper(uriString, false, uriKind, ref e);
return (object)e == null && result != null;
}
public static bool TryCreate(Uri baseUri, string relativeUri, out Uri result)
{
Uri relativeLink;
if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink))
{
if (!relativeLink.IsAbsoluteUri)
return TryCreate(baseUri, relativeLink, out result);
result = relativeLink;
return true;
}
result = null;
return false;
}
public static bool TryCreate(Uri baseUri, Uri relativeUri, out Uri result)
{
result = null;
if ((object)baseUri == null || (object)relativeUri == null)
return false;
if (baseUri.IsNotAbsoluteUri)
return false;
UriFormatException e;
string newUriString = null;
bool dontEscape;
if (baseUri.Syntax.IsSimple)
{
dontEscape = relativeUri.UserEscaped;
result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e);
}
else
{
dontEscape = false;
newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e);
}
if (e != null)
return false;
if ((object)result == null)
result = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
return (object)e == null && result != null && result.IsAbsoluteUri;
}
public string GetComponents(UriComponents components, UriFormat format)
{
if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString)
throw new ArgumentOutOfRangeException(nameof(components), components, SR.net_uri_NotJustSerialization);
if ((format & ~UriFormat.SafeUnescaped) != 0)
throw new ArgumentOutOfRangeException(nameof(format));
if (IsNotAbsoluteUri)
{
if (components == UriComponents.SerializationInfoString)
return GetRelativeSerializationString(format);
else
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
if (Syntax.IsSimple)
return GetComponentsHelper(components, format);
return Syntax.InternalGetComponents(this, components, format);
}
//
// This is for languages that do not support == != operators overloading
//
// Note that Uri.Equals will get an optimized path but is limited to true/false result only
//
public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat,
StringComparison comparisonType)
{
if ((object)uri1 == null)
{
if (uri2 == null)
return 0; // Equal
return -1; // null < non-null
}
if ((object)uri2 == null)
return 1; // non-null > null
// a relative uri is always less than an absolute one
if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri)
return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString,
uri2.OriginalString, comparisonType);
return string.Compare(
uri1.GetParts(partsToCompare, compareFormat),
uri2.GetParts(partsToCompare, compareFormat),
comparisonType
);
}
public bool IsWellFormedOriginalString()
{
if (IsNotAbsoluteUri || Syntax.IsSimple)
return InternalIsWellFormedOriginalString();
return Syntax.InternalIsWellFormedOriginalString(this);
}
public static bool IsWellFormedUriString(string uriString, UriKind uriKind)
{
Uri result;
if (!Uri.TryCreate(uriString, uriKind, out result))
return false;
return result.IsWellFormedOriginalString();
}
//
// Internal stuff
//
// Returns false if OriginalString value
// (1) is not correctly escaped as per URI spec excluding intl UNC name case
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
//
internal unsafe bool InternalIsWellFormedOriginalString()
{
if (UserDrivenParsing)
throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType()));
fixed (char* str = _string)
{
ushort idx = 0;
//
// For a relative Uri we only care about escaping and backslashes
//
if (!IsAbsoluteUri)
{
// my:scheme/path?query is not well formed because the colon is ambiguous
if (CheckForColonInFirstPathSegment(_string))
{
return false;
}
return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL)
& (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical;
}
//
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
//
if (IsImplicitFile)
return false;
//This will get all the offsets, a Host name will be checked separately below
EnsureParseRemaining();
Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical));
// Cleanup canonical IRI from nonCanonical
if ((nonCanonical & (Flags.UserIriCanonical | Flags.PathIriCanonical | Flags.QueryIriCanonical | Flags.FragmentIriCanonical)) != 0)
{
if ((nonCanonical & (Flags.E_UserNotCanonical | Flags.UserIriCanonical)) == (Flags.E_UserNotCanonical | Flags.UserIriCanonical))
{
nonCanonical = nonCanonical & ~(Flags.E_UserNotCanonical | Flags.UserIriCanonical);
}
if ((nonCanonical & (Flags.E_PathNotCanonical | Flags.PathIriCanonical)) == (Flags.E_PathNotCanonical | Flags.PathIriCanonical))
{
nonCanonical = nonCanonical & ~(Flags.E_PathNotCanonical | Flags.PathIriCanonical);
}
if ((nonCanonical & (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical)) == (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical))
{
nonCanonical = nonCanonical & ~(Flags.E_QueryNotCanonical | Flags.QueryIriCanonical);
}
if ((nonCanonical & (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical)) == (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical))
{
nonCanonical = nonCanonical & ~(Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical);
}
}
// User, Path, Query or Fragment may have some non escaped characters
if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical |
Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero))
{
return false;
}
// checking on scheme:\\ or file:////
if (InFact(Flags.AuthorityFound))
{
idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2);
if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\')
return false;
if (InFact(Flags.UncPath | Flags.DosPath))
{
while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\'))
return false;
}
}
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash
// (which looks absent) then the method has to fail.
// Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check.
if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path)
return false;
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
// Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid
if (InFact(Flags.BackslashInPath))
return false;
// Capturing a rare case like file:///c|/dir
if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|')
return false;
//
// May need some real CPU processing to answer the request
//
//
// Check escaping for authority
//
// IPv6 hosts cannot be properly validated by CheckCannonical
if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType)
{
idx = _info.Offset.User;
Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/');
if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical))
!= Check.EscapedCanonical)
&& (!_iriParsing || (_iriParsing
&& ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical))
!= (Check.DisplayCanonical | Check.FoundNonAscii)))))
{
return false;
}
}
// Want to ensure there are slashes after the scheme
if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound))
== (Flags.SchemeNotCanonical | Flags.AuthorityFound))
{
idx = (ushort)_syntax.SchemeName.Length;
while (str[idx++] != ':') ;
if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/')
return false;
}
}
//
// May be scheme, host, port or path need some canonicalization but still the uri string is found to be a
// "well formed" one
//
return true;
}
public static string UnescapeDataString(string stringToUnescape)
{
if ((object)stringToUnescape == null)
throw new ArgumentNullException(nameof(stringToUnescape));
if (stringToUnescape.Length == 0)
return string.Empty;
unsafe
{
fixed (char* pStr = stringToUnescape)
{
int position;
for (position = 0; position < stringToUnescape.Length; ++position)
if (pStr[position] == '%')
break;
if (position == stringToUnescape.Length)
return stringToUnescape;
UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll;
position = 0;
char[] dest = new char[stringToUnescape.Length];
dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position,
c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false);
return new string(dest, 0, position);
}
}
}
//
// Where stringToEscape is intended to be a completely unescaped URI string.
// This method will escape any character that is not a reserved or unreserved character, including percent signs.
// Note that EscapeUriString will also do not escape a '#' sign.
//
public static string EscapeUriString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true,
c_DummyChar, c_DummyChar, c_DummyChar);
if ((object)dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Where stringToEscape is intended to be URI data, but not an entire URI.
// This method will escape any character that is not an unreserved character, including percent signs.
//
public static string EscapeDataString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false,
c_DummyChar, c_DummyChar, c_DummyChar);
if (dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Cleans up the specified component according to Iri rules
// a) Chars allowed by iri in a component are unescaped if found escaped
// b) Bidi chars are stripped
//
// should be called only if IRI parsing is switched on
internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component)
{
fixed (char* pInput = input)
{
return IriHelper.EscapeUnescapeIri(pInput, start, end, component);
}
}
// Should never be used except by the below method
private Uri(Flags flags, UriParser uriParser, string uri)
{
_flags = flags;
_syntax = uriParser;
_string = uri;
}
//
// a Uri.TryCreate() method goes through here.
//
internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
UriParser syntax = null;
Flags flags = Flags.Zero;
ParsingError err = ParseScheme(uriString, ref flags, ref syntax);
if (dontEscape)
flags |= Flags.UserEscaped;
// We won't use User factory for these errors
if (err != ParsingError.None)
{
// If it looks as a relative Uri, custom factory is ignored
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
return new Uri((flags & Flags.UserEscaped), null, uriString);
return null;
}
// Cannot be relative Uri if came here
Uri result = new Uri(flags, syntax, uriString);
// Validate instance using ether built in or a user Parser
try
{
result.InitializeUri(err, uriKind, out e);
if (e == null)
return result;
return null;
}
catch (UriFormatException ee)
{
Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate.");
e = ee;
// A precaution since custom Parser should never throw in this case.
return null;
}
}
//
// Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString
// to return combined URI strings from both Uris
// otherwise if e != null on output the operation has failed
//
internal static Uri ResolveHelper(Uri baseUri, Uri relativeUri, ref string newUriString, ref bool userEscaped,
out UriFormatException e)
{
Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser.");
e = null;
string relativeStr = string.Empty;
if ((object)relativeUri != null)
{
if (relativeUri.IsAbsoluteUri)
return relativeUri;
relativeStr = relativeUri.OriginalString;
userEscaped = relativeUri.UserEscaped;
}
else
relativeStr = string.Empty;
// Here we can assert that passed "relativeUri" is indeed a relative one
if (relativeStr.Length > 0 && (UriHelper.IsLWS(relativeStr[0]) || UriHelper.IsLWS(relativeStr[relativeStr.Length - 1])))
relativeStr = relativeStr.Trim(UriHelper.s_WSchars);
if (relativeStr.Length == 0)
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri,
baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped);
return null;
}
// Check for a simple fragment in relative part
if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveFragment))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check for a simple query in relative part
if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveQuery))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check on the DOS path in the relative Uri (a special case)
if (relativeStr.Length >= 3
&& (relativeStr[1] == ':' || relativeStr[1] == '|')
&& UriHelper.IsAsciiLetter(relativeStr[0])
&& (relativeStr[2] == '\\' || relativeStr[2] == '/'))
{
if (baseUri.IsImplicitFile)
{
// It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri
newUriString = relativeStr;
return null;
}
else if (baseUri.Syntax.InFact(UriSyntaxFlags.AllowDOSPath))
{
// The scheme is not changed just the path gets replaced
string prefix;
if (baseUri.InFact(Flags.AuthorityFound))
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://";
else
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":";
newUriString = baseUri.Scheme + prefix + relativeStr;
return null;
}
// If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x
}
ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString);
if (err != ParsingError.None)
{
e = GetException(err);
return null;
}
if ((object)newUriString == (object)baseUri._string)
return baseUri;
return null;
}
private unsafe string GetRelativeSerializationString(UriFormat format)
{
if (format == UriFormat.UriEscaped)
{
if (_string.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true,
c_DummyChar, c_DummyChar, '%');
if ((object)dest == null)
return _string;
return new string(dest, 0, position);
}
else if (format == UriFormat.Unescaped)
return UnescapeDataString(_string);
else if (format == UriFormat.SafeUnescaped)
{
if (_string.Length == 0)
return string.Empty;
char[] dest = new char[_string.Length];
int position = 0;
dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar,
c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false);
return new string(dest, 0, position);
}
else
throw new ArgumentOutOfRangeException(nameof(format));
}
//
// UriParser helpers methods
//
internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat)
{
if (uriComponents == UriComponents.Scheme)
return _syntax.SchemeName;
// A serialization info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case
if ((uriComponents & UriComponents.SerializationInfoString) != 0)
uriComponents |= UriComponents.AbsoluteUri;
//This will get all the offsets, HostString will be created below if needed
EnsureParseRemaining();
if ((uriComponents & UriComponents.NormalizedHost) != 0)
{
// Down the path we rely on Host to be ON for NormalizedHost
uriComponents |= UriComponents.Host;
}
//Check to see if we need the host/authority string
if ((uriComponents & UriComponents.Host) != 0)
EnsureHostString(true);
//This, single Port request is always processed here
if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort)
{
if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort
&& _syntax.DefaultPort != UriParser.NoDefaultPort))
{
// recreate string from the port value
return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture);
}
return string.Empty;
}
if ((uriComponents & UriComponents.StrongPort) != 0)
{
// Down the path we rely on Port to be ON for StrongPort
uriComponents |= UriComponents.Port;
}
//This request sometime is faster to process here
if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped
|| ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0)))
{
EnsureHostString(false);
return _info.Host;
}
switch (uriFormat)
{
case UriFormat.UriEscaped:
return GetEscapedParts(uriComponents);
case V1ToStringUnescape:
case UriFormat.SafeUnescaped:
case UriFormat.Unescaped:
return GetUnescapedParts(uriComponents, uriFormat);
default:
throw new ArgumentOutOfRangeException(nameof(uriFormat));
}
}
public bool IsBaseOf(Uri uri)
{
if ((object)uri == null)
throw new ArgumentNullException(nameof(uri));
if (!IsAbsoluteUri)
return false;
if (Syntax.IsSimple)
return IsBaseOfHelper(uri);
return Syntax.InternalIsBaseOf(this, uri);
}
internal bool IsBaseOfHelper(Uri uriLink)
{
if (!IsAbsoluteUri || UserDrivenParsing)
return false;
if (!uriLink.IsAbsoluteUri)
{
//a relative uri could have quite tricky form, it's better to fix it now.
string newUriString = null;
UriFormatException e;
bool dontEscape = false;
uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e);
if (e != null)
return false;
if ((object)uriLink == null)
uriLink = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
if (e != null)
return false;
}
if (Syntax.SchemeName != uriLink.Syntax.SchemeName)
return false;
// Canonicalize and test for substring match up to the last path slash
string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
unsafe
{
fixed (char* selfPtr = self)
{
fixed (char* otherPtr = other)
{
return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length,
IsUncOrDosPath || uriLink.IsUncOrDosPath);
}
}
}
}
//
// Only a ctor time call
//
private void CreateThisFromUri(Uri otherUri)
{
// Clone the other guy but develop own UriInfo member
_info = null;
_flags = otherUri._flags;
if (InFact(Flags.MinimalUriInfoSet))
{
_flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask);
// Port / Path offset
int portIndex = otherUri._info.Offset.Path;
if (InFact(Flags.NotDefaultPort))
{
// Find the start of the port. Account for non-canonical ports like :00123
while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host)
{
portIndex--;
}
if (otherUri._string[portIndex] != ':')
{
// Something wrong with the NotDefaultPort flag. Reset to path index
Debug.Fail("Uri failed to locate custom port at index: " + portIndex);
portIndex = otherUri._info.Offset.Path;
}
}
_flags |= (Flags)portIndex; // Port or path
}
_syntax = otherUri._syntax;
_string = otherUri._string;
_iriParsing = otherUri._iriParsing;
if (otherUri.OriginalStringSwitched)
{
_originalUnicodeString = otherUri._originalUnicodeString;
}
if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost)))
{
_dnsSafeHost = otherUri._dnsSafeHost;
}
}
}
}
| |
/*
* SymBinder.cs - Implementation of the
* "System.Diagnostics.SymbolStore.SymBinder" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Diagnostics.SymbolStore
{
#if CONFIG_EXTENDED_DIAGNOSTICS
using System.IO;
public class SymBinder : ISymbolBinder
{
// Constructor.
public SymBinder() {}
// Destructor (C++ style).
~SymBinder() {}
public void __dtor()
{
GC.SuppressFinalize(this);
Finalize();
}
// Create a symbol reader for a file. Will set "wasBinary" to
// true if the file is a PE/COFF binary that does not contain
// debug symbol information. Returns null if the file does not
// contain debug symbol information.
private static ISymbolReader CreateReader
(String filename, out bool wasBinary)
{
FileStream stream;
byte[] buffer = new byte [1024];
byte[] section;
int len, offset;
// Clear the "wasBinary" flag before we start.
wasBinary = false;
// Open the file.
try
{
stream = new FileStream
(filename, FileMode.Open, FileAccess.Read);
}
catch(Exception)
{
return null;
}
try
{
// Check the magic number to determine the file type.
if(stream.Read(buffer, 0, 8) != 8)
{
return null;
}
if(buffer[0] == (byte)'I' &&
buffer[1] == (byte)'L' &&
buffer[2] == (byte)'D' &&
buffer[3] == (byte)'B' &&
buffer[4] == (byte)0x01 &&
buffer[5] == (byte)0x00 &&
buffer[6] == (byte)0x00 &&
buffer[7] == (byte)0x00)
{
// This is a standalone debug symbol file.
len = (int)(stream.Length);
section = new byte [len];
Array.Copy(buffer, 0, section, 0, 8);
stream.Read(section, 8, len - 8);
return new SymReader(filename, section);
}
else if(buffer[0] == (byte)'M' &&
buffer[1] == (byte)'Z')
{
// We are processing a binary for embedded symbols.
wasBinary = true;
// Skip past the MS-DOS stub portion of the binary.
stream.Read(buffer, 8, 64 - 8);
offset = Utils.ReadInt32(buffer, 60);
if(offset < 64)
{
return null;
}
stream.Position = offset;
// Read the PE/COFF header.
stream.Read(buffer, 0, 24);
if(buffer[0] != (byte)'P' ||
buffer[1] != (byte)'E' ||
buffer[2] != (byte)0x00 ||
buffer[3] != (byte)0x00)
{
return null;
}
Array.Copy(buffer, 4, buffer, 0, 20);
}
else if(buffer[0] == (byte)0x4C &&
buffer[1] == (byte)0x01)
{
// This is a PE/COFF object file: read the rest
// of the PE/COFF header into memory.
stream.Read(buffer, 8, 20 - 8);
}
else
{
// We don't know what format the file is in.
return null;
}
// If we get here, then we have a PE/COFF header
// in "buffer", minus the "PE".
int numSections = Utils.ReadUInt16(buffer, 2);
int headerSize = Utils.ReadUInt16(buffer, 16);
if(headerSize != 0 &&
(headerSize < 216 || headerSize > 1024))
{
return null;
}
if(numSections == 0)
{
return null;
}
// Skip the optional header.
stream.Seek(headerSize, SeekOrigin.Current);
// Search the section table for ".ildebug".
while(numSections > 0)
{
if(stream.Read(buffer, 0, 40) != 40)
{
return null;
}
if(buffer[0] == (byte)'.' &&
buffer[1] == (byte)'i' &&
buffer[2] == (byte)'l' &&
buffer[3] == (byte)'d' &&
buffer[4] == (byte)'e' &&
buffer[5] == (byte)'b' &&
buffer[6] == (byte)'u' &&
buffer[7] == (byte)'g')
{
// Skip to the debug data and read it.
offset = Utils.ReadInt32(buffer, 20);
len = Utils.ReadInt32(buffer, 8);
stream.Position = offset;
section = new byte [len];
stream.Read(section, 0, len);
return new SymReader(filename, section);
}
--numSections;
}
}
finally
{
stream.Close();
}
// We were unable to find the debug symbols if we get here.
return null;
}
// Get a symbol reader for a particular file.
public virtual ISymbolReader GetReader
(int importer, String filename, String searchPath)
{
// Try the file in its specified location.
if(File.Exists(filename))
{
return GetReader(filename);
}
// Bail out if the filename was absolute, or there is no path.
if(Path.IsPathRooted(filename))
{
throw new ArgumentException();
}
else if(searchPath == null || searchPath.Length == 0)
{
throw new ArgumentException();
}
// Search the path for the file.
int posn = 0;
int index1, index2;
String dir;
String combined;
while(posn < searchPath.Length)
{
// Find the next path separator.
index1 = searchPath.IndexOf(Path.PathSeparator, posn);
if(Path.PathSeparator == ':')
{
// Unix-like system: use either ":" or ";" to separate.
index2 = searchPath.IndexOf(';', posn);
if(index2 != -1 && index2 < index1)
{
index1 = index2;
}
}
if(index1 == -1)
{
index1 = searchPath.Length;
}
// Extract the directory from the path.
dir = searchPath.Substring(posn, index1 - posn).Trim();
posn = index1 + 1;
if(dir.Length == 0)
{
continue;
}
// See if the specified file exists.
combined = Path.Combine(dir, filename);
if(File.Exists(combined))
{
return GetReader(combined);
}
}
// We were unable to find the file.
throw new ArgumentException();
}
private static ISymbolReader GetReader(String filename)
{
ISymbolReader reader;
bool wasBinary;
// Try to create a symbol reader for the file itself.
reader = CreateReader(filename, out wasBinary);
if(reader != null)
{
return reader;
}
// If the file was a PE/COFF binary that does not
// include debug symbol information, then look for
// the "*.pdb" file corresponding to the binary.
if(wasBinary)
{
filename = Path.ChangeExtension(filename, "pdb");
reader = CreateReader(filename, out wasBinary);
if(reader != null)
{
return reader;
}
}
// We were unable to locate the debug symbols.
throw new ArgumentException();
}
}; // class SymBinder
#endif // CONFIG_EXTENDED_DIAGNOSTICS
}; // namespace System.Diagnostics.SymbolStore
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.Globalization;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.IO;
using UWin32;
using System.Threading;
using System.Text;
using System.Diagnostics;
namespace bg
{
public class MealCharter : GraphicBox
{
class MPG
{
MP m_mp;
ArrayList m_plsbge;
public MPG(MP mp)
{
m_mp = mp;
}
public ArrayList Plsbge { get { return m_plsbge; } set { m_plsbge = value; } }
public MP Mp { get { return m_mp; } set { m_mp = value; } }
}
ArrayList m_plmp;
int m_impFirst;
VScrollBar m_sbv;
HScrollBar m_sbh;
GrapherParams m_gp;
RectangleF m_rcf;
ArrayList m_plmpg;
float m_dxOffsetForSbge;
float m_dyOffsetForSbge;
public MealCharter(RectangleF rcf, Graphics gr)
{
m_rcf = rcf;
}
public void Paint(Graphics gr)
{
// int yTopBase = (int)sbge.RectF.Top + 17;
foreach (MPG mpg in m_plmpg)
{
Font font = new Font("Tahoma", 10);
SolidBrush brushBlue = new SolidBrush(Color.Blue);
Pen pen = new Pen(brushBlue, 1);
SBGE sbge = (SBGE)mpg.Plsbge[0];
const int dxSep = 30;
const int dxLeft = 20;
int xLeft = (int)m_rcf.Left + dxLeft;
int yTop = (int)sbge.RectF.Top;
MP mp = mpg.Mp;
gr.DrawString(mp.SGetDescription(), font, brushBlue, sbge.RectF.Left - 150, yTop - 15);
gr.DrawRectangle(pen, xLeft - 4, yTop, dxSep * 4 + 4, 43);
gr.DrawLine(pen, xLeft + dxSep - 1, yTop, xLeft + dxSep - 1, yTop + 43);
gr.DrawLine(pen, xLeft + dxSep * 2 - 1, yTop, xLeft + dxSep * 2 - 1, yTop + 43);
gr.DrawLine(pen, xLeft + dxSep * 3 - 1, yTop, xLeft + dxSep * 3 - 1, yTop + 43);
gr.DrawLine(pen, xLeft - 4, yTop + 20, xLeft + dxSep * 4, yTop + 20);
gr.DrawString("M+0", font, brushBlue, xLeft, yTop + 3);
gr.DrawString("M+1", font, brushBlue, xLeft + dxSep * 1, yTop + 3);
gr.DrawString("M+2", font, brushBlue, xLeft + dxSep * 2, yTop + 3);
gr.DrawString("M+4", font, brushBlue, xLeft + dxSep * 3, yTop + 3);
for (int i = 0; i < 4; i++)
{
gr.DrawString(mp.NGetAvgForMpt((MP.MPT)i).ToString(), font, brushBlue, xLeft + i * dxSep, yTop + 23);
}
yTop += 50;
xLeft = (int)m_rcf.Left + dxLeft + 30;
gr.DrawRectangle(pen, xLeft - 4, yTop, dxSep * 2 + 4, 43);
gr.DrawLine(pen, xLeft + dxSep - 1, yTop, xLeft + dxSep - 1, yTop + 43);
gr.DrawLine(pen, xLeft - 4, yTop + 20, xLeft + dxSep * 2, yTop + 20);
gr.DrawString("Post", font, brushBlue, xLeft, yTop + 3);
gr.DrawString("Morn", font, brushBlue, xLeft + dxSep * 1, yTop + 3);
for (int i = 0; i < 2; i++)
{
gr.DrawString(mp.NGetAvgForMpt((MP.MPT)i + 4).ToString(), font, brushBlue, xLeft + i * dxSep, yTop + 23);
}
sbge.SetNoCurves();
sbge.PaintGraphGridlines(gr);
foreach (SBGE sbgeT in mpg.Plsbge)
{
sbgeT.PaintGraph(gr);
}
}
}
public void SetFirstFromScroll(int i)
{
m_impFirst = i;
}
public void Calc()
{
RectangleF rcf = new RectangleF(m_rcf.Left + 180.0f, m_rcf.Top + 25.0f, m_rcf.Width - 150.0f, 100.0f);
// we are going to have a number of graphs on the page;
// calc them all.
// let's assume we're only graphing one for now
m_plmpg = new ArrayList();
foreach (MP mp in m_plmp)
{
// graph the meals
MPG mpg = new MPG(mp);
mpg.Plsbge = new ArrayList();
int i = 0, iMac = mp.NGetSampleSize();
for (i = 0; i < iMac; i++)
{
SBGE sbge = new SBGE(m_gp, m_dxOffsetForSbge, m_dyOffsetForSbge + 15.0f, false);
sbge.Tag = mp;
sbge.SetDataSet(mp.SlbgeForSample(i), null);
sbge.SetMealLegend(mp.DttmMealForSample(i));
sbge.SetLineWidth(0.2f);
sbge.CalcGraph(rcf);
mpg.Plsbge.Add(sbge);
}
m_plmpg.Add(mpg);
rcf.Y += 140.0f;
// rcf = new RectangleF(m_rcf.Left + 120.0f, m_rcf.Top + 110.0f, m_rcf.Width - 150.0f, 100.0f);
// i = 0;
// iMac = mp.NGetSampleSize();
// for (i = 0; i < iMac; i++)
// {
// SBGE sbge = new SBGE(m_gp, m_dxOffsetForSbge, m_dyOffsetForSbge, false);
//
// sbge.SetDataSet(mp.SlbgeForSample(i), null);
// sbge.SetMealLegend(mp.DttmMealForSample(i));
// sbge.SetLineWidth(0.2f);
// sbge.CalcGraph(rcf);
// mpg.Plsbge.Add(sbge);
// }
// m_plmpg.Add(mpg);
}
}
public bool FHitTest(Point pt, out object oHit, out RectangleF rectfHit)
{
oHit = null;
rectfHit = new RectangleF();
return false;
}
public void SetDataPoints(object oData, VScrollBar sbv, HScrollBar sbh)
{
m_plmp = (ArrayList)oData;
m_sbv = sbv;
m_sbh = sbh;
}
public void SetProps(GrapherParams gp)
{
m_gp = gp;
}
public int GetFirstForScroll()
{
return m_impFirst;
}
public void SetColor(bool fColor)
{
}
public int GetDaysPerPage()
{
return 0;
}
public void SetDaysPerPage(int nDaysPerPage)
{
}
public DateTime GetFirstDateTime()
{
return new DateTime(2005, 01, 01);
}
public void SetFirstDateTime(DateTime dttm)
{
}
public bool FGetLastDateTimeOnPage(out DateTime dttm)
{
dttm = new DateTime(2005, 01, 01);
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.Utilities;
namespace OpenMetaverse.TestClient
{
public class TestClient : GridClient
{
public UUID GroupID = UUID.Zero;
public Dictionary<UUID, GroupMember> GroupMembers;
public Dictionary<UUID, AvatarAppearancePacket> Appearances = new Dictionary<UUID, AvatarAppearancePacket>();
public Dictionary<string, Command> Commands = new Dictionary<string, Command>();
public bool Running = true;
public bool GroupCommands = false;
public string MasterName = String.Empty;
public UUID MasterKey = UUID.Zero;
public bool AllowObjectMaster = false;
public ClientManager ClientManager;
public VoiceManager VoiceManager;
// Shell-like inventory commands need to be aware of the 'current' inventory folder.
public InventoryFolder CurrentDirectory = null;
private System.Timers.Timer updateTimer;
private UUID GroupMembersRequestID;
public Dictionary<UUID, Group> GroupsCache = null;
private ManualResetEvent GroupsEvent = new ManualResetEvent(false);
/// <summary>
///
/// </summary>
public TestClient(ClientManager manager)
{
ClientManager = manager;
updateTimer = new System.Timers.Timer(500);
updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);
RegisterAllCommands(Assembly.GetExecutingAssembly());
Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
Settings.LOG_RESENDS = false;
Settings.STORE_LAND_PATCHES = true;
Settings.ALWAYS_DECODE_OBJECTS = true;
Settings.ALWAYS_REQUEST_OBJECTS = true;
Settings.SEND_AGENT_UPDATES = true;
Settings.USE_ASSET_CACHE = true;
Network.RegisterCallback(PacketType.AgentDataUpdate, AgentDataUpdateHandler);
Network.LoginProgress += LoginHandler;
Objects.AvatarUpdate += new EventHandler<AvatarUpdateEventArgs>(Objects_AvatarUpdate);
Objects.TerseObjectUpdate += new EventHandler<TerseObjectUpdateEventArgs>(Objects_TerseObjectUpdate);
Network.SimChanged += new EventHandler<SimChangedEventArgs>(Network_SimChanged);
Self.IM += Self_IM;
Groups.GroupMembersReply += GroupMembersHandler;
Inventory.InventoryObjectOffered += Inventory_OnInventoryObjectReceived;
Network.RegisterCallback(PacketType.AvatarAppearance, AvatarAppearanceHandler);
Network.RegisterCallback(PacketType.AlertMessage, AlertMessageHandler);
VoiceManager = new VoiceManager(this);
updateTimer.Start();
}
void Objects_TerseObjectUpdate(object sender, TerseObjectUpdateEventArgs e)
{
if (e.Prim.LocalID == Self.LocalID)
{
SetDefaultCamera();
}
}
void Objects_AvatarUpdate(object sender, AvatarUpdateEventArgs e)
{
if (e.Avatar.LocalID == Self.LocalID)
{
SetDefaultCamera();
}
}
void Network_SimChanged(object sender, SimChangedEventArgs e)
{
Self.Movement.SetFOVVerticalAngle(Utils.TWO_PI - 0.05f);
}
public void SetDefaultCamera()
{
// SetCamera 5m behind the avatar
Self.Movement.Camera.LookAt(
Self.SimPosition + new Vector3(-5, 0, 0) * Self.Movement.BodyRotation,
Self.SimPosition
);
}
void Self_IM(object sender, InstantMessageEventArgs e)
{
bool groupIM = e.IM.GroupIM && GroupMembers != null && GroupMembers.ContainsKey(e.IM.FromAgentID) ? true : false;
if (e.IM.FromAgentID == MasterKey || (GroupCommands && groupIM))
{
// Received an IM from someone that is authenticated
Console.WriteLine("<{0} ({1})> {2}: {3} (@{4}:{5})", e.IM.GroupIM ? "GroupIM" : "IM", e.IM.Dialog, e.IM.FromAgentName, e.IM.Message,
e.IM.RegionID, e.IM.Position);
if (e.IM.Dialog == InstantMessageDialog.RequestTeleport)
{
Console.WriteLine("Accepting teleport lure.");
Self.TeleportLureRespond(e.IM.FromAgentID, e.IM.IMSessionID, true);
}
else if (
e.IM.Dialog == InstantMessageDialog.MessageFromAgent ||
e.IM.Dialog == InstantMessageDialog.MessageFromObject)
{
ClientManager.Instance.DoCommandAll(e.IM.Message, e.IM.FromAgentID);
}
}
else
{
// Received an IM from someone that is not the bot's master, ignore
Console.WriteLine("<{0} ({1})> {2} (not master): {3} (@{4}:{5})", e.IM.GroupIM ? "GroupIM" : "IM", e.IM.Dialog, e.IM.FromAgentName, e.IM.Message,
e.IM.RegionID, e.IM.Position);
return;
}
}
/// <summary>
/// Initialize everything that needs to be initialized once we're logged in.
/// </summary>
/// <param name="login">The status of the login</param>
/// <param name="message">Error message on failure, MOTD on success.</param>
public void LoginHandler(object sender, LoginProgressEventArgs e)
{
if (e.Status == LoginStatus.Success)
{
// Start in the inventory root folder.
CurrentDirectory = Inventory.Store.RootFolder;
}
}
public void RegisterAllCommands(Assembly assembly)
{
foreach (Type t in assembly.GetTypes())
{
try
{
if (t.IsSubclassOf(typeof(Command)))
{
ConstructorInfo info = t.GetConstructor(new Type[] { typeof(TestClient) });
Command command = (Command)info.Invoke(new object[] { this });
RegisterCommand(command);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
public void RegisterCommand(Command command)
{
command.Client = this;
if (!Commands.ContainsKey(command.Name.ToLower()))
{
Commands.Add(command.Name.ToLower(), command);
}
}
public void ReloadGroupsCache()
{
Groups.CurrentGroups += Groups_CurrentGroups;
Groups.RequestCurrentGroups();
GroupsEvent.WaitOne(10000, false);
Groups.CurrentGroups -= Groups_CurrentGroups;
GroupsEvent.Reset();
}
void Groups_CurrentGroups(object sender, CurrentGroupsEventArgs e)
{
if (null == GroupsCache)
GroupsCache = e.Groups;
else
lock (GroupsCache) { GroupsCache = e.Groups; }
GroupsEvent.Set();
}
public UUID GroupName2UUID(String groupName)
{
UUID tryUUID;
if (UUID.TryParse(groupName,out tryUUID))
return tryUUID;
if (null == GroupsCache) {
ReloadGroupsCache();
if (null == GroupsCache)
return UUID.Zero;
}
lock(GroupsCache) {
if (GroupsCache.Count > 0) {
foreach (Group currentGroup in GroupsCache.Values)
if (currentGroup.Name.ToLower() == groupName.ToLower())
return currentGroup.ID;
}
}
return UUID.Zero;
}
private void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
foreach (Command c in Commands.Values)
if (c.Active)
c.Think();
}
private void AgentDataUpdateHandler(object sender, PacketReceivedEventArgs e)
{
AgentDataUpdatePacket p = (AgentDataUpdatePacket)e.Packet;
if (p.AgentData.AgentID == e.Simulator.Client.Self.AgentID)
{
GroupID = p.AgentData.ActiveGroupID;
GroupMembersRequestID = e.Simulator.Client.Groups.RequestGroupMembers(GroupID);
}
}
private void GroupMembersHandler(object sender, GroupMembersReplyEventArgs e)
{
if (e.RequestID != GroupMembersRequestID) return;
GroupMembers = e.Members;
}
private void AvatarAppearanceHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet;
lock (Appearances) Appearances[appearance.Sender.ID] = appearance;
}
private void AlertMessageHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
AlertMessagePacket message = (AlertMessagePacket)packet;
Logger.Log("[AlertMessage] " + Utils.BytesToString(message.AlertData.Message), Helpers.LogLevel.Info, this);
}
private void Inventory_OnInventoryObjectReceived(object sender, InventoryObjectOfferedEventArgs e)
{
if (MasterKey != UUID.Zero)
{
if (e.Offer.FromAgentID != MasterKey)
return;
}
else if (GroupMembers != null && !GroupMembers.ContainsKey(e.Offer.FromAgentID))
{
return;
}
e.Accept = true;
return;
}
}
}
| |
//
// TagStore.cs
//
// Author:
// Ettore Perazzoli <[email protected]>
// Stephane Delcroix <[email protected]>
// Larry Ewing <[email protected]>
//
// Copyright (C) 2003-2009 Novell, Inc.
// Copyright (C) 2003 Ettore Perazzoli
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2004-2006 Larry Ewing
//
// 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;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Jobs;
using FSpot.Utils;
using Hyena;
using Hyena.Data.Sqlite;
using Mono.Unix;
namespace FSpot {
public class InvalidTagOperationException : InvalidOperationException {
public InvalidTagOperationException (Tag t, string message) : base (message)
{
Tag = t;
}
public Tag Tag { get; set; }
}
// Sorts tags into an order that it will be safe to delete
// them in (eg children first).
public class TagRemoveComparer : IComparer {
public int Compare (object obj1, object obj2)
{
Tag t1 = obj1 as Tag;
Tag t2 = obj2 as Tag;
return Compare (t1, t2);
}
public int Compare (Tag t1, Tag t2)
{
if (t1.IsAncestorOf (t2))
return 1;
if (t2.IsAncestorOf (t1))
return -1;
return 0;
}
}
public class TagStore : DbStore<Tag>, IDisposable {
bool disposed;
public Category RootCategory { get; private set; }
public Tag Hidden { get; private set; }
const string STOCK_ICON_DB_PREFIX = "stock_icon:";
static void SetIconFromString (Tag tag, string iconString)
{
if (iconString == null) {
tag.Icon = null;
// IconWasCleared automatically set already, override
// it in this case since it was NULL in the db.
tag.IconWasCleared = false;
} else if (iconString == String.Empty)
tag.Icon = null;
else if (iconString.StartsWith (STOCK_ICON_DB_PREFIX, StringComparison.Ordinal))
tag.ThemeIconName = iconString.Substring (STOCK_ICON_DB_PREFIX.Length);
else
tag.Icon = GdkUtils.Deserialize (Convert.FromBase64String (iconString));
}
public Tag GetTagByName (string name)
{
foreach (Tag t in item_cache.Values)
if (t.Name.ToLower () == name.ToLower ())
return t;
return null;
}
public Tag GetTagById (int id)
{
foreach (Tag t in item_cache.Values)
if (t.Id == id)
return t;
return null;
}
public Tag [] GetTagsByNameStart (string s)
{
List <Tag> l = new List<Tag> ();
foreach (Tag t in item_cache.Values) {
if (t.Name.ToLower ().StartsWith (s.ToLower ()))
l.Add (t);
}
if (l.Count == 0)
return null;
l.Sort ((t1, t2) => t2.Popularity.CompareTo (t1.Popularity));
return l.ToArray ();
}
// In this store we keep all the items (i.e. the tags) in memory at all times. This is
// mostly to simplify handling of the parent relationship between tags, but it also makes it
// a little bit faster. We achieve this by passing "true" as the cache_is_immortal to our
// base class.
void LoadAllTags ()
{
// Pass 1, get all the tags.
IDataReader reader = Database.Query ("SELECT id, name, is_category, sort_priority, icon FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
string name = reader ["name"].ToString ();
bool is_category = (Convert.ToUInt32 (reader ["is_category"]) != 0);
Tag tag;
if (is_category)
tag = new Category (null, id, name);
else
tag = new Tag (null, id, name);
if (reader ["icon"] != null)
try {
SetIconFromString (tag, reader ["icon"].ToString ());
} catch (Exception ex) {
Log.Exception ("Unable to load icon for tag " + name, ex);
}
tag.SortPriority = Convert.ToInt32 (reader["sort_priority"]);
AddToCache (tag);
}
reader.Dispose ();
// Pass 2, set the parents.
reader = Database.Query ("SELECT id, category_id FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
uint category_id = Convert.ToUInt32 (reader ["category_id"]);
Tag tag = Get (id);
if (tag == null)
throw new Exception (String.Format ("Cannot find tag {0}", id));
if (category_id == 0)
tag.Category = RootCategory;
else {
tag.Category = Get (category_id) as Category;
if (tag.Category == null)
Log.Warning ("Tag Without category found");
}
}
reader.Dispose ();
//Pass 3, set popularity
reader = Database.Query ("SELECT tag_id, COUNT (*) AS popularity FROM photo_tags GROUP BY tag_id");
while (reader.Read ()) {
Tag t = Get (Convert.ToUInt32 (reader ["tag_id"]));
if (t != null)
t.Popularity = Convert.ToInt32 (reader ["popularity"]);
}
reader.Dispose ();
if (App.Instance.Database.Meta.HiddenTagId.Value != null)
Hidden = LookupInCache ((uint)App.Instance.Database.Meta.HiddenTagId.ValueAsInt);
}
void CreateTable ()
{
Database.Execute (
"CREATE TABLE tags (\n" +
" id INTEGER PRIMARY KEY NOT NULL, \n" +
" name TEXT UNIQUE, \n" +
" category_id INTEGER, \n" +
" is_category BOOLEAN, \n" +
" sort_priority INTEGER, \n" +
" icon TEXT\n" +
")");
}
void CreateDefaultTags ()
{
Category favorites_category = CreateCategory (RootCategory, Catalog.GetString ("Favorites"), false);
favorites_category.ThemeIconName = "emblem-favorite";
favorites_category.SortPriority = -10;
Commit (favorites_category);
Tag hidden_tag = CreateTag (RootCategory, Catalog.GetString ("Hidden"), false);
hidden_tag.ThemeIconName = "emblem-readonly";
hidden_tag.SortPriority = -9;
Hidden = hidden_tag;
Commit (hidden_tag);
App.Instance.Database.Meta.HiddenTagId.ValueAsInt = (int) hidden_tag.Id;
App.Instance.Database.Meta.Commit (App.Instance.Database.Meta.HiddenTagId);
Tag people_category = CreateCategory (RootCategory, Catalog.GetString ("People"), false);
people_category.ThemeIconName = "emblem-people";
people_category.SortPriority = -8;
Commit (people_category);
Tag places_category = CreateCategory (RootCategory, Catalog.GetString ("Places"), false);
places_category.ThemeIconName = "emblem-places";
places_category.SortPriority = -8;
Commit (places_category);
Tag events_category = CreateCategory (RootCategory, Catalog.GetString ("Events"), false);
events_category.ThemeIconName = "emblem-event";
events_category.SortPriority = -7;
Commit (events_category);
}
// Constructor
public TagStore (FSpotDatabaseConnection database, bool isNew)
: base (database, true)
{
// The label for the root category is used in new and edit tag dialogs
RootCategory = new Category (null, 0, Catalog.GetString ("(None)"));
if (! isNew) {
LoadAllTags ();
} else {
CreateTable ();
CreateDefaultTags ();
}
}
uint InsertTagIntoTable (Category parentCategory, string name, bool isCategory, bool autoicon)
{
uint parent_category_id = parentCategory.Id;
String default_tag_icon_value = autoicon ? null : String.Empty;
long id = Database.Execute (new HyenaSqliteCommand ("INSERT INTO tags (name, category_id, is_category, sort_priority, icon)"
+ "VALUES (?, ?, ?, 0, ?)",
name,
parent_category_id,
isCategory ? 1 : 0,
default_tag_icon_value));
// The table in the database is setup to be an INTEGER.
return (uint) id;
}
public Tag CreateTag (Category category, string name, bool autoicon)
{
if (category == null)
category = RootCategory;
uint id = InsertTagIntoTable (category, name, false, autoicon);
Tag tag = new Tag (category, id, name);
tag.IconWasCleared = !autoicon;
AddToCache (tag);
EmitAdded (tag);
return tag;
}
public Category CreateCategory (Category parentCategory, string name, bool autoicon)
{
if (parentCategory == null)
parentCategory = RootCategory;
uint id = InsertTagIntoTable (parentCategory, name, true, autoicon);
Category new_category = new Category (parentCategory, id, name);
new_category.IconWasCleared = !autoicon;
AddToCache (new_category);
EmitAdded (new_category);
return new_category;
}
public override Tag Get (uint id)
{
return id == 0 ? RootCategory : LookupInCache (id);
}
public override void Remove (Tag item)
{
Category category = item as Category;
if (category != null &&
category.Children != null &&
category.Children.Count > 0)
throw new InvalidTagOperationException (category, "Cannot remove category that contains children");
RemoveFromCache (item);
item.Category = null;
Database.Execute (new HyenaSqliteCommand ("DELETE FROM tags WHERE id = ?", item.Id));
EmitRemoved (item);
}
string GetIconString (Tag tag)
{
if (tag.ThemeIconName != null)
return STOCK_ICON_DB_PREFIX + tag.ThemeIconName;
if (tag.Icon == null) {
if (tag.IconWasCleared)
return String.Empty;
return null;
}
byte [] data = GdkUtils.Serialize (tag.Icon);
return Convert.ToBase64String (data);
}
public override void Commit (Tag item)
{
Commit (item, false);
}
public void Commit (Tag tag, bool updateXmp)
{
Commit (new Tag[] {tag}, updateXmp);
}
public void Commit (Tag [] tags, bool updateXmp)
{
// TODO.
bool use_transactions = updateXmp;//!Database.InTransaction && update_xmp;
//if (use_transactions)
// Database.BeginTransaction ();
// FIXME: this hack is used, because HyenaSqliteConnection does not support
// the InTransaction propery
if (use_transactions) {
try {
Database.BeginTransaction ();
} catch {
use_transactions = false;
}
}
foreach (Tag tag in tags) {
Database.Execute (new HyenaSqliteCommand ("UPDATE tags SET name = ?, category_id = ?, "
+ "is_category = ?, sort_priority = ?, icon = ? WHERE id = ?",
tag.Name,
tag.Category.Id,
tag is Category ? 1 : 0,
tag.SortPriority,
GetIconString (tag),
tag.Id));
if (updateXmp && Preferences.Get<bool> (Preferences.METADATA_EMBED_IN_IMAGE)) {
Photo [] photos = App.Instance.Database.Photos.Query (new Tag [] { tag });
foreach (Photo p in photos)
if (p.HasTag (tag)) // the query returns all the pics of the tag and all its child. this avoids updating child tags
SyncMetadataJob.Create (App.Instance.Database.Jobs, p);
}
}
if (use_transactions)
Database.CommitTransaction ();
EmitChanged (tags);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
disposed = true;
if (disposing) {
// free managed resources
foreach (Tag tag in item_cache.Values) {
tag.Dispose ();
}
item_cache.Clear ();
if (RootCategory != null) {
RootCategory.Dispose ();
RootCategory = null;
}
}
// free unmanaged resources
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.IO;
using System.ComponentModel;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Asserts on Files
/// </summary>
public static class FileAssert
{
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE! Use FileAssert.AreEqual(...) instead.
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("FileAssert.Equals should not be used. Use FileAssert.AreEqual instead.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("FileAssert.ReferenceEquals should not be used.");
}
#endregion
#region AreEqual
#region Streams
/// <summary>
/// Verifies that two Streams are equal. Two Streams are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(Stream expected, Stream actual, string message, params object[] args)
{
Assert.That(actual, Is.EqualTo(expected), message, args);
}
/// <summary>
/// Verifies that two Streams are equal. Two Streams are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
static public void AreEqual(Stream expected, Stream actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#region FileInfo
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(FileInfo expected, FileInfo actual, string message, params object[] args)
{
using (FileStream exStream = expected.OpenRead())
using (FileStream acStream = actual.OpenRead())
{
AreEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
static public void AreEqual(FileInfo expected, FileInfo actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(string expected, string actual, string message, params object[] args)
{
using (FileStream exStream = File.OpenRead(expected))
using (FileStream acStream = File.OpenRead(actual))
{
AreEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
static public void AreEqual(string expected, string actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#endregion
#region AreNotEqual
#region Streams
/// <summary>
/// Asserts that two Streams are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
/// <param name="message">The message to be displayed when the two Stream are the same.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(Stream expected, Stream actual, string message, params object[] args)
{
Assert.That(actual, Is.Not.EqualTo(expected), message, args);
}
/// <summary>
/// Asserts that two Streams are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
static public void AreNotEqual(Stream expected, Stream actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#region FileInfo
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(FileInfo expected, FileInfo actual, string message, params object[] args)
{
using (FileStream exStream = expected.OpenRead())
using (FileStream acStream = actual.OpenRead())
{
AreNotEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
static public void AreNotEqual(FileInfo expected, FileInfo actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(string expected, string actual, string message, params object[] args)
{
using (FileStream exStream = File.OpenRead(expected))
using (FileStream acStream = File.OpenRead(actual))
{
AreNotEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
static public void AreNotEqual(string expected, string actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#endregion
#region Exists
#region FileInfo
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Exists(FileInfo actual, string message, params object[] args)
{
Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args);
}
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
static public void Exists(FileInfo actual)
{
Exists(actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Exists(string actual, string message, params object[] args)
{
Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args);
}
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
static public void Exists(string actual)
{
Exists(actual, string.Empty, null);
}
#endregion
#endregion
#region DoesNotExist
#region FileInfo
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void DoesNotExist(FileInfo actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args);
}
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
static public void DoesNotExist(FileInfo actual)
{
DoesNotExist(actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void DoesNotExist(string actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args);
}
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
static public void DoesNotExist(string actual)
{
DoesNotExist(actual, string.Empty, null);
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Thunder.Extensions;
using Thunder.Web.Mvc.Extensions;
namespace Thunder.Web.Mvc
{
/// <summary>
/// Notify result
/// </summary>
public class NotifyResult : ActionResult
{
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
public NotifyResult()
{
Type = NotifyType.Success;
Messages = new List<KeyValuePair<string, IList<string>>>();
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="message">Message</param>
public NotifyResult(string message)
: this(NotifyType.Success, message)
{
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="type"><see cref="NotifyType"/></param>
/// <param name="message">Message</param>
public NotifyResult(NotifyType type, string message)
: this(type, new List<string> { message })
{
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="messages">Messages</param>
public NotifyResult(IEnumerable<string> messages)
: this(NotifyType.Success, messages)
{
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="type"><see cref="NotifyType"/></param>
/// <param name="messages">Messages</param>
public NotifyResult(NotifyType type, IEnumerable<string> messages) : this()
{
Type = type;
Messages = messages.Select(message => new KeyValuePair<string, IList<string>>(Guid.NewGuid().ToString(), new List<string> { message })).ToList();
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="notify"><see cref="Notify"/></param>
public NotifyResult(Notify notify)
{
Type = notify.Type;
Messages = notify.Messages.Select(message => new KeyValuePair<string, IList<string>>(Guid.NewGuid().ToString(), new List<string> { message })).ToList();
}
/// <summary>
/// Initialize new instance of class <see cref="NotifyResult"/>.
/// </summary>
/// <param name="type"><see cref="NotifyType"/></param>
/// <param name="modelState"><see cref="IDictionary{TKey,TValue}"/></param>
public NotifyResult(NotifyType type, IDictionary<string, ModelState> modelState)
: this()
{
Type = type;
Messages = modelState.ToKeyAndValues().ToList();
}
/// <summary>
/// Get or set type
/// </summary>
public NotifyType Type { get; private set; }
/// <summary>
/// Get or set messages
/// </summary>
public IList<KeyValuePair<string, IList<string>>> Messages { get; private set; }
/// <summary>
/// Get or set content encoding
/// </summary>
public Encoding ContentEncoding { get; set; }
/// <summary>
/// Get an set content type
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Get or set json request behavior
/// </summary>
public JsonRequestBehavior JsonRequestBehavior { get; set; }
/// <summary>
/// Get or set data result
/// </summary>
public object Data { get; set; }
/// <summary>
/// Execute result
/// </summary>
/// <param name="context"></param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if(context.HttpContext.Request.IsAjaxRequest())
{
Ajax(context);
}
else
{
Html(context);
}
}
private void Ajax(ControllerContext context)
{
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("HttpMethot GET not allowed.");
}
var response = context.HttpContext.Response;
var json = JsonConvert.SerializeObject(new { Type, Messages },
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (!string.IsNullOrEmpty(context.HttpContext.Request["callback"]))
{
json = string.Format("{0}({1})", context.HttpContext.Request["callback"], json);
}
context.HttpContext.Response.Write(json);
}
private void Html(ControllerContext context)
{
var builder = new StringBuilder();
var messages = new StringBuilder();
if(Messages.Count > 0)
{
if(Messages.Count == 1)
{
messages.Append(Messages[0]);
}
else
{
messages.Append("<ul>");
foreach (var message in Messages)
{
messages.Append("<li>{0}</li>".With(message));
}
messages.Append("</ul>");
}
}
builder.Append("<div class=\"alert{0}\">".With(CssClass()))
.Append("<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>")
.Append(messages)
.Append("</div>");
context.HttpContext.Response.Write(builder.ToString());
}
private string CssClass()
{
var cssClass = string.Empty;
switch (Type)
{
case NotifyType.Danger:
cssClass = " alert-danger";
break;
case NotifyType.Information:
cssClass = " alert-info";
break;
case NotifyType.Success:
cssClass = " alert-success";
break;
case NotifyType.Warning:
cssClass = " alert-warning";
break;
}
return cssClass;
}
}
}
| |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using Common.Logging;
using Spring.Context;
using Spring.Context.Support;
using Spring.Util;
namespace Spring.Testing.NUnit
{
/// <summary>
/// Superclass for NUnit test cases using a Spring context.
/// </summary>
/// <remarks>
/// <p>Maintains a cache of contexts by key. This has significant performance
/// benefit if initializing the context would take time. While initializing a
/// Spring context itself is very quick, some objects in a context, such as
/// a LocalSessionFactoryObject for working with NHibernate, may take time to
/// initialize. Hence it often makes sense to do that initializing once.</p>
/// <p>Normally you won't extend this class directly but rather extend one
/// of its subclasses.</p>
/// </remarks>
/// <author>Rod Johnson</author>
/// <author>Aleksandar Seovic (.NET)</author>
public abstract class AbstractSpringContextTests
{
/// <summary>
/// Map of context keys returned by subclasses of this class, to
/// Spring contexts.
/// </summary>
private static readonly IDictionary contextKeyToContextMap;
/// <summary>
/// Static ctor to avoid "beforeFieldInit" problem.
/// </summary>
static AbstractSpringContextTests()
{
contextKeyToContextMap = new Hashtable();
}
/// <summary>
/// Disposes any cached context instance and removes it from cache.
/// </summary>
public static void ClearContextCache()
{
foreach(IApplicationContext ctx in contextKeyToContextMap.Values)
{
ctx.Dispose();
}
contextKeyToContextMap.Clear();
}
/// <summary>
/// Indicates, whether context instances should be automatically registered with the global <see cref="ContextRegistry"/>.
/// </summary>
private bool registerContextWithContextRegistry = true;
/// <summary>
/// Logger available to subclasses.
/// </summary>
protected readonly ILog logger;
/// <summary>
/// Default constructor for AbstractSpringContextTests.
/// </summary>
protected AbstractSpringContextTests()
{
logger = LogManager.GetLogger(GetType());
}
/// <summary>
/// Controls, whether application context instances will
/// be registered/unregistered with the global <see cref="ContextRegistry"/>.
/// Defaults to <c>true</c>.
/// </summary>
public bool RegisterContextWithContextRegistry
{
get { return registerContextWithContextRegistry; }
set { registerContextWithContextRegistry = value; }
}
/// <summary>
/// Set custom locations dirty. This will cause them to be reloaded
/// from the cache before the next test case is executed.
/// </summary>
/// <remarks>
/// Call this method only if you change the state of a singleton
/// object, potentially affecting future tests.
/// </remarks>
/// <param name="locations">Locations </param>
protected void SetDirty(string[] locations)
{
SetDirty((object)locations);
}
/// <summary>
/// Set context with <paramref name="contextKey"/> dirty. This will cause
/// it to be reloaded from the cache before the next test case is executed.
/// </summary>
/// <remarks>
/// Call this method only if you change the state of a singleton
/// object, potentially affecting future tests.
/// </remarks>
/// <param name="contextKey">Locations </param>
protected void SetDirty(object contextKey)
{
String keyString = ContextKeyString(contextKey);
IConfigurableApplicationContext ctx =
(IConfigurableApplicationContext) contextKeyToContextMap[keyString];
contextKeyToContextMap.Remove(keyString);
if (ctx != null)
{
ctx.Dispose();
}
}
/// <summary>
/// Returns <c>true</c> if context for the specified
/// <paramref name="contextKey"/> is cached.
/// </summary>
/// <param name="contextKey">Context key to check.</param>
/// <returns>
/// <c>true</c> if context for the specified
/// <paramref name="contextKey"/> is cached,
/// <c>false</c> otherwise.
/// </returns>
protected bool HasCachedContext(object contextKey)
{
string keyString = ContextKeyString(contextKey);
return contextKeyToContextMap.Contains(keyString);
}
/// <summary>
/// Converts context key to string.
/// </summary>
/// <remarks>
/// Subclasses can override this to return a string representation of
/// their contextKey for use in logging.
/// </remarks>
/// <param name="contextKey">Context key to convert.</param>
/// <returns>
/// String representation of the specified <paramref name="contextKey"/>. Null if
/// contextKey is null.
/// </returns>
protected virtual string ContextKeyString(object contextKey)
{
if (contextKey == null)
{
return null;
}
if (contextKey is string[])
{
return StringUtils.CollectionToCommaDelimitedString((string[])contextKey);
}
else
{
return contextKey.ToString();
}
}
/// <summary>
/// Caches application context.
/// </summary>
/// <param name="key">Key to use.</param>
/// <param name="context">Context to cache.</param>
public void AddContext(object key, IConfigurableApplicationContext context)
{
AssertUtils.ArgumentNotNull(context, "context", "ApplicationContext must not be null");
string keyString = ContextKeyString(key);
contextKeyToContextMap.Add(keyString, context);
if (RegisterContextWithContextRegistry
&& !ContextRegistry.IsContextRegistered(context.Name))
{
ContextRegistry.RegisterContext(context);
}
}
/// <summary>
/// Returns cached context if present, or loads it if not.
/// </summary>
/// <param name="key">Context key.</param>
/// <returns>Spring application context associated with the specified key.</returns>
protected IConfigurableApplicationContext GetContext(object key)
{
string keyString = ContextKeyString(key);
IConfigurableApplicationContext ctx =
(IConfigurableApplicationContext) contextKeyToContextMap[keyString];
if (ctx == null)
{
if (key is string[])
{
ctx = LoadContextLocations((string[]) key);
}
else
{
ctx = LoadContext(key);
}
AddContext(key, ctx);
}
return ctx;
}
/// <summary>
/// Loads application context from the specified resource locations.
/// </summary>
/// <param name="locations">Resources to load object definitions from.</param>
protected virtual IConfigurableApplicationContext LoadContextLocations(string[] locations)
{
if (logger.IsInfoEnabled)
{
logger.Info("Loading config for: " + StringUtils.CollectionToCommaDelimitedString(locations));
}
return new XmlApplicationContext(locations);
}
/// <summary>
/// Loads application context based on user-defined key.
/// </summary>
/// <remarks>
/// Unless overriden by the user, this method will alway throw
/// a <see cref="NotSupportedException"/>.
/// </remarks>
/// <param name="key">User-defined key.</param>
protected virtual IConfigurableApplicationContext LoadContext(object key)
{
throw new NotSupportedException("Subclasses may override this");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.